Find the ancestor chain of p and Q from top to bottom, until root exists in the array respectively, and then find the smallest common ancestor


    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; }}; 'answer reference: 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;
    }
    
Copy the code