面试经典题:二叉树最近公共祖先

二叉树的最近公共祖先

面试经典题:最近公共祖先,提供三种思路:1、模拟路径,2、dfs,3、dfs优化

class Solution {
public:    
    bool dfs(TreeNode* root, TreeNode* t, vector<TreeNode*>&path){
        if(!root) return false;
        if(root == t){
            path.push_back(root);
            return true;
        }
        if(dfs(root->left,t,path) || dfs(root->right,t,path)){
            path.push_back(root);
            return true;
        }
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        vector<TreeNode*> a,b;
        dfs(root, p, a);
        dfs(root, q, b);
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());

        int n=min(a.size(), b.size());
        for(int i=n-1;i>=0;i--){
            if(a[i] == b[i]) return a[i];
        }
        return NULL;
    }
};
class Solution {
public:
    TreeNode* ans=NULL;
    int dfs(TreeNode*root, TreeNode*p, TreeNode*q){
        if(!root) return 0;
        int state=dfs(root->left,p,q) | dfs(root->right,p,q);
        if(root==p) state|=1;
        else if(root==q) state|=2;
        if(state==3 && !ans) ans=root;
        return state;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root,p,q);
        return ans;
    }
};
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || root==p || root==q) return root;
        auto l=lowestCommonAncestor(root->left,p,q);
        auto r=lowestCommonAncestor(root->right,p,q);
        if(!l) return r;
        if(!r) return l;
        return root;
    }
};
posted @ 2022-04-08 23:36  SrtFrmGNU  阅读(26)  评论(0编辑  收藏  举报