在二叉树中找到两个节点的最近公共祖先

108 阅读1分钟

image.png 题意:给出2个节点,找出这2个节点的最近公共祖先\

想法:创建一个unordered_map类型的vis标志,如果自己、左子树、右子树中任意一个包含目标节点,就标志为true,如果有任意2个中包含目标节点,那这个节点就是最近公共祖先。

class Solution {
public:
    unordered_map<int, bool> vis;
    int result;
    void dfs(TreeNode *root,int o1,int o2) {
        int cnt=0;//表示节点权重
        //自己是目标节点就让cnt++
        if(root->val == o1 || root->val == o2) {
            vis[root->val] = true;
            ++cnt;
        }
    
        if(root->left !=nullptr) {
            dfs(root->left, o1, o2);
            //左子树中有目标节点,让cnt++
            if(vis[root->left->val]) ++cnt;
        }
        if(root->right !=nullptr) {
            dfs(root->right, o1, o2);
            //右子树中有目标节点,cnt++
            if(vis[root->right->val]) ++cnt;
        }
        if(cnt>0) vis[root->val] = true;
        //自己,左子树、右子树中如果任意2个中含有目标节点,那么这个就是目标节点
        if(cnt==2) result = root->val;
    }

    int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
        // write code here
        if(o1 == o2) return o1;

        vis.clear(),result=0;
        dfs(root, o1, o2);
        return result;
    }
};