/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* preorder(struct TreeNode* root,struct TreeNode* p,struct TreeNode* q){
if(!root) return NULL;
if(root==p) return p;
if(root==q) return q;
struct TreeNode* left=preorder(root->left,p,q);
struct TreeNode* right=preorder(root->right,p,q);
if(!right&&!left) return NULL;
if(left==p&&right==q || left==q&&right==p) return root;
if(left&&!right) return left;
return right;
}
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if(root==p||root==q) return root;
return preorder(root,p,q);
}
结果:
标签:right,TreeNode,struct,二叉,return,搜索,235,root,left From: https://www.cnblogs.com/llllmz/p/18057425