[leetcode] LowestCommonAncestor

LowestCommonAncestor

  • 问题描述:给定一颗二叉树,和二叉树的两个节点,计算出这两个节点的最低公公祖先。
  • 解法1:
    • 最低公公祖先可能出现的最高值就是根节点。
    • 我们找到从根节点到两个节点的路径,path1和path2.
    • 则两者一定是Y字型或者是V字形(root节点)
    • 则我们就把问题转化成了计算两个list的相交点问题。
    • 首先长的path先走他们之间长度差值步,使得后续的两个path长度一致。
    • 然后再同时向后走,第一个相遇的点就是LCA
  • 解法2 (DP):
    • 拆分子问题:我们可以判断左子树和右子树是否包含这两个节点其中的一个。
    • 构造父问题:如果左子树和右子树都包含两个节点中的一个,则返回当前的根节点。如果只有左子树包含,则返回左子树的根节点,如果只有右子树包含,则返回右子树的根节点。
  • 代码
bool findPath(TreeNode* root, TreeNode* target, vector<TreeNode*>& path){
        if(root == NULL){
            return false;
        }
        if(root == target){
            path.push_back(root);
            return true;
        }
        bool left_res = findPath(root->left, target, path);
        if(left_res){
            path.push_back(root);
            return true;
        }
        bool right_res = findPath(root->right, target, path);
        if(right_res){
            path.push_back(root);
            return true;
        }
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == NULL)
            return NULL;
        vector<TreeNode*> path_p, path_q;
        findPath(root, p, path_p);
        findPath(root, q, path_q);
        if(path_p.empty() || path_q.empty())
            return NULL;
        int size_p = (int) path_p.size();
        int size_q = (int) path_q.size();
        int start_p = 0;
        int start_q = 0;
        if(size_p >= size_q){
            start_p = size_p - size_q;
        }else{
            start_q = size_q - size_p;
        }
        for(;start_p < size_p && start_q < size_q;start_p++, start_q++){
            if(path_p[start_p] == path_q[start_q])
                return path_p[start_p];
        }
        return NULL;
    }
    TreeNode* lowestCommonAncestorV2(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || root == p || root == q)
            return root;
        TreeNode* left = lowestCommonAncestorV2(root->left, p, q); // 在左孩子中找寻找q或者p
        TreeNode* right = lowestCommonAncestorV2(root->right, p, q); // 在右子树中尝试寻找p或者q
        // 如果左孩子找到了,右孩子没找打,则是左孩子
        // 如果两个都找到了,则是root
        return left == NULL ? right: right == NULL ? left : root;
        // return !left ? right : !right ? left : root;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值