Leetcode 236 - Lowest Common Ancestor of a Binary Tree (LCA)

16 篇文章 0 订阅

链接

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

题意

给一个二叉树,求两个节点的LCA

思路

求LCA有很多算法, 有基于RMQ的离线算法,也有倍增,不过这两个写起来稍微麻烦一点。
这里写简单一点的方法

算法1

假设我们知道每个节点的父节点是谁,求p和q的LCA时,我们先求出这两个节点的高度len1和len2,假设 len1>len2 ,那么p先向上走 len1len2 步来弥补差距,然后p和q同时往上一步一步的走,直到他俩相遇
然后父节点信息的话dfs一遍记录一下就好

算法2

有点类似leetcode235求BST的LCA的思路:
对于当前节点now,我们分别去左右子树分别查找是否有目标节点p和q,并且记录找到的位置
1. 如果左右子树都有目标节点,那么now就是LCA
2. 如果只有左子树有目标节点,那么我们第一个找到目标节点的位置就是LCA
3. 如果只有右子树有目标节点,那么我们第一个找到目标节点的位置就是LCA

代码

算法1

/**
 * 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 {
private:
    unordered_map<TreeNode*, TreeNode*> parent;
    int len1, len2;
    TreeNode *p, *q;
public:
    void dfs(TreeNode* now, TreeNode* pa, int dep) {
        if (!now) return;
        if (now == p) len1 = dep;
        if (now == q) len2 = dep;
        parent[now] = pa;
        dfs(now->left, now, dep + 1);
        dfs(now->right, now, dep + 1);
    }

    TreeNode* LCA(TreeNode* p, TreeNode* q) {
        while (len1 > len2) {
            p = parent[p];
            len1--;
        }
        while (len2 > len1) {
            q = parent[q];
            len2--;
        }
        while (len1) {
            if (p == q) return p;
            p = parent[p];
            q = parent[q];
            len1--;
            len2--;
        }
        return NULL;
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root) return NULL;
        this->p = p;
        this->q = q;
        dfs(root, NULL, 1);
        return LCA(p, q);
    }
};

算法2

/**
 * 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root || p == root || q == root) return root;
        TreeNode* lch = lowestCommonAncestor(root->left, p, q);
        TreeNode* rch = lowestCommonAncestor(root->right, p, q);
        if (lch && rch) return root;
        return lch ? lch : rch;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值