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

https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

递归实现最近公共祖先,函数返回该子树是否包含p,q。有两种情况,1.p、q在同一条路径上,所以需要找到了p或者q继续向下查找,找到了了的话最近公共祖先就是这个。2.p,q在两条支路上,那么最近公共祖先的左右子树各包含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 find(TreeNode* root, TreeNode* p, TreeNode* q){
        if(root==NULL)
            return false;
        if(root==p||root==q){
            bool ret1=find(root->left,p,q);
            bool ret2=find(root->right,p,q);
            if(ret1||ret2){
                ans=root;
            }
            return true;
        }
        else{
            bool ret1=find(root->left,p,q);
            bool ret2=find(root->right,p,q);
            if(ret1&&ret2)
                ans=root;
            return ret1||ret2;
        }
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        ans=NULL;
        find(root,p,q);
        return ans;
    }
};

 

这个是求父节点和深度版本的。

/**
 * 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:
    map<TreeNode*,TreeNode*> father;
    map<TreeNode*,int> depth;

    void get_father(TreeNode *root,int d){
        if(root==NULL)
            return;
        depth[root]=d;
        if(root->left){
            father[root->left]=root;
        }
        if(root->right)
            father[root->right]=root;
        get_father(root->left,d+1);
        get_father(root->right,d+1);
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        get_father(root,0);
        int depth_p=depth[p];
        int depth_q=depth[q];

        if(depth_p<depth_q){//p more depth
            swap(depth_p,depth_q);
            swap(p,q);
        }
        while(depth_p>depth_q){
            p=father[p];
            depth_p--;
        }

        while(p!=q){
            p=father[p];
            q=father[q];
        }
        return p;
        
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值