//找到第一个共同祖先
class Solution{
//若p为root的子孙,则返回true
bool covers(TreeNode*root, TreeNode*p){
if(NULL == root)
return false;
if(root == p)
return true;
return covers(root->left,p)||covers(root->right,p);
}
TreeNode* commonAncestorHelper(TreeNode*root, TreeNode*p, TreeNode*q){
if(root==NULL)
return NULL;
if(root==p || root==q)
return root;
bool is_p_on_left=covers(root->left,p);
bool is_q_on_right=covers(root->right,q);
//若p和q不在同一边,则返回root
if(is_p_on_left != is_q_on_right)
return root;
//否则就在同一边,遍访那一边
TreeNode* child_side = is_p_on_left?root->left:root->right;
return commonAncestorHelper(child_side,p,q);
}
TreeNode* commonAncetor(TreeNode*root, TreeNode*p, TreeNode*q){
if(!covers(root,p) || !covers(root,q)) //错误检查
return NULL;
return commonAncestorHelper(root,p,q);
}
};
//找到最近祖先
class Solution{
TreeNode* lowestCommonAnceston(TreeNode* root, TreeNode* A, TreeNode* B){
if(NULL==root || root==A || root==B)
return NULL;
TreeNode* left = lowestCommonAnceston(root->left,A,B);
TreeNode* root = lowestCommonAnceston(root->right,A,B);
if(left && right)
return root;
return left?left:right;
}
};