236. 二叉树的最近公共祖先

class Solution {
public:
    bool dfs(TreeNode* root,TreeNode* target,vector<TreeNode*>&path){
        path.emplace_back(root);
        if(root->val==target->val) 
            return true;
        if(root->left&& dfs(root->left,target,path)) 
             return true;
        if(root->right&&dfs(root->right,target,path)) 
            return true;
        path.pop_back();
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        vector<TreeNode*>path1,path2;
        dfs(root,p,path1);
        dfs(root,q,path2);
        int len=min(path1.size(),path2.size());
        TreeNode* ans=root;
        for(int i=1;i<len;++i){
            if(path1[i]!=path2[i]){
                return ans;
            }
            ans=path1[i];
        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode,深度优先,算法,leetcode)