其他分享
首页 > 其他分享> > 236. 二叉树的最近公共祖先

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

作者:互联网

要求:rt
法一:有两种情况,一是分在两边(公共祖先不是pq),一是在一边(祖先为p或q)。具体一点,一是左右子树分别包含pq(这样的点是唯一的),二是若左子树包含pq并且左节点是pq则左节点就是,右边同理

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* ans;
    bool dfs(TreeNode* root,TreeNode* p,TreeNode* q){
        if(!root)return false;
        bool lb=dfs(root->left,p,q);
        bool rb=dfs(root->right,p,q);
        if(lb&&rb)ans=root;
        if(lb&&(root==p||root==q))ans=root;
        if(rb&&(root==p||root==q))ans=root;
        if((lb||rb)||(root==p||root==q))return true;//要么自己是,要么子树包含,都得返回true
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root,p,q);
        return ans;
    }
};

法二:map记录每个节点的祖先,再从pq遍历回去第一个重复的

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    unordered_map<TreeNode*,TreeNode*> ancestor;
    void dfs(TreeNode* root){
        if(!root)return;
        if(root->left){
            ancestor[root->left]=root;
            dfs(root->left);
        }
        if(root->right){
            ancestor[root->right]=root;
            dfs(root->right);
        }
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        unordered_map<TreeNode*,bool> visited;
        TreeNode* ans;
        dfs(root);
        while(p){
            visited[p]=true;
            p=ancestor[p];
        }
        while(q){
            if(visited[q]){
                ans=q;
                break;
            }
            q=ancestor[q];
        }
        return ans;
    }
};

标签:right,TreeNode,祖先,dfs,二叉树,ans,236,root,left
来源: https://blog.csdn.net/cx_cs/article/details/122226168