树中两个结点的最低公共祖先

class Solution {
public:
    vector<TreeNode*> t;
    void dfs(TreeNode* root,TreeNode* p,vector<TreeNode*> &q)
    {
        if(!root)   return;
        t.push_back(root);
        if(root==p)
        {
            q=t;
            t.pop_back();
            return;
        }
        dfs(root->left,p,q);
        dfs(root->right,p,q);
        t.pop_back();
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        vector<TreeNode*> path1,path2;
        dfs(root,q,path1);
        dfs(root,p,path2);
        for (int i = min(path1.size()-1,path2.size()-1); i >= 0; i -- )
            if(path1[i]==path2[i])  return path1[i];
        return NULL;
    }
};
posted @ 2023-05-19 15:16  穿过雾的阴霾  阅读(20)  评论(0)    收藏  举报