从上之下一次找p和q的祖先链条,一直找到root 分别存在数组里面 然后找公共的祖先的最小的那个
bool rootIsFatherOf(vector<TreeNode*> &ve,TreeNode* root,TreeNode* p){
if(root == nullptr){
return false;
}
if(root == p){
return true;
}
else if( rootIsFatherOf(ve,root->left,p) ){
ve.push_back(root->left);
return true;
}
else if( rootIsFatherOf(ve,root->right,p) ){
ve.push_back(root->right);
return true;
}else{
return false;
}
return false;
}
};
`
答案参考: https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/comments/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left == nullptr && right == nullptr) return nullptr;
else if(left != nullptr && right != nullptr) return root;
else return left == nullptr ? right : left;
}