思路:递归的思想,如果当前节点的左子树和右子树各包括一个节点,则该节点就为最近公共祖先;如果当前节点等于其中的一个节点,则当前节点为最近公共祖先;如果当前节点的左子树或者右子树包括两个节点,则需要递归求该节点的左子树或者有子树。
struct Node{
int data;
Node* left, *right;
};
//count the number of p and q
//这个函数这样写的很巧妙,如果将root==p||root==q
//写在前面的话,我们将分不清另一个节点所在的子树就会比较麻烦
int getNumpq(Node *root,Node *p,Node *q){
if(!root) return 0;
int res=getNumpq(root->left,p,q)+getNumpq(root->right,p,q);
if(root==p||root==q)
return 1+res;
else
return res;
}
//Lowest Common Ancestor
Node* LCA(Node *root,Node *p,Node *q){
if(!root||!p||!q) return NULL;
if(root==p||root==q) return root;
int matches=getNumpq(root->left,p,q);
if(matches==1)
return root;
else if(matches==2)
return LCA(root->left,p,q);
else
return LCA(root->right,p,q);
}