python coding with ChatGPT 打卡第21天| 二叉树:最近公共祖先

相关推荐
python coding with ChatGPT 打卡第12天| 二叉树:理论基础
python coding with ChatGPT 打卡第13天| 二叉树的深度优先遍历
python coding with ChatGPT 打卡第14天| 二叉树的广度优先遍历
python coding with ChatGPT 打卡第15天| 二叉树:翻转二叉树、对称二叉树
python coding with ChatGPT 打卡第16天| 二叉树:完全二叉树、平衡二叉树、二叉树的所有路径、左叶子之和
python coding with ChatGPT 打卡第17天| 二叉树:找树左下角的值、路径总和
python coding with ChatGPT 打卡第18天| 二叉树:从中序与后序遍历序列构造二叉树、最大二叉树
python coding with ChatGPT 打卡第19天| 二叉树:合并二叉树
python coding with ChatGPT 打卡第20天| 二叉搜索树:搜索、验证、最小绝对差、众数

二叉树的最近公共祖先

Key Points

  • 后序遍历(左右中)就是天然的回溯过程,可以根据左右子树的返回值,来处理中节点的逻辑。
  • 判断逻辑是 如果递归遍历遇到q,就将q返回,遇到p 就将p返回,那么如果 左右子树的返回值都不为空,说明此时的中节点,一定是q 和p 的最近祖先。

相关题目

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

视频讲解

自底向上查找,有点难度

重点分析

方法一:递归法

  1. 递归的终止条件:
  • 遇到空的话,因为树都是空了,所以返回空。
  • 如果 root == q,或者 root == p,说明找到 q p ,则将其返回,这个返回值,后面在中节点的处理过程中会用到
  1. 单层处理逻辑:
  • 如果left 和 right都不为空,说明此时root就是最近公共节点。这个比较好理解
  • 如果left为空,right不为空,就返回right,说明目标节点是通过right返回的,反之依然。
def lowestCommonAncestor(root, p, q):
    if not root:
        return root
    if root == p or root == q:
        return root
    left = lowestCommonAncestor(root.left, p, q)
    right = lowestCommonAncestor(root.right, p, q)
    if left and right:
        return root
    if left:
        return left
    if right:
        return right
    return None

在这里插入图片描述

评价:
直接使用一次遍历来找到最近公共祖先会更高效。这种方法不需要存储所有父节点的路径,而是利用递归在回溯过程中直接找到LCA。

方法二:递归法
首先为每个节点找到其所有的父节点,然后比较这两个列表来找到最近的公共父节点

def find_all_father(root, p):
    res = []
    def find_father(root, p):
        if not root:
            return False
        if root == p or find_father(root.left, p) or find_father(root.right, p):
            res.append(root)
            return True
        return False
    find_father(root, p)
    return res

def lowestCommonAncestor(root, p, q):
    res1 = find_all_father(root, p)
    res2 = find_all_father(root, q)
    for i in res1:
        for j in res2:
            if i == j:
                return i

评价:
对于每个节点p和q,你的方法都会遍历整棵树来找到它们的所有父节点。这意味着树被遍历了两次。此外,对于找到的每对父节点,你使用了双层循环来比较它们,这会导致效率低下,尤其是在大树上。

方法三:迭代法
在这里插入图片描述

def lowestCommonAncestor(root, p, q):
    # 字典用于保存每个节点的父节点
    parent = {root: None}
    stack = [root]
    
    # 迭代遍历树,直到找到p和q
    while p not in parent or q not in parent:
        node = stack.pop()
        if node.left:
            parent[node.left] = node
            stack.append(node.left)
        if node.right:
            parent[node.right] = node
            stack.append(node.right)
    
    # 通过父节点字典构建p到根节点的路径
    ancestors = set()
    while p:
        ancestors.add(p)
        p = parent[p]
    
    # 检查q到根节点的路径中第一个出现在p路径集合中的节点
    while q not in ancestors:
        q = parent[q]
    return q

这个代码首先使用一个栈和一个字典来迭代遍历整棵树并记录每个节点的父节点。然后,它构建了从p到根节点的路径并保存在一个集合中。最后,它追溯q到根节点的路径,直到找到第一个也出现在p的路径集合中的节点。这个节点就是p和q的最近公共祖先。

评价:
这个方法避免了递归,但需要额外的存储空间来记录父节点信息,并且需要两次遍历:一次是构建父节点的映射,一次是构建从目标节点到根节点的路径。

二叉搜索树的最近公共祖先

Key Points

在二叉搜索树(BST)中找到两个指定节点的最近公共祖先(LCA)比在普通二叉树中要简单,因为你可以利用BST的性质:对于任何节点,左子树上的所有节点的值都小于该节点的值,右子树上的所有节点的值都大于该节点的值。这个性质允许我们使用迭代或递归的方式来快速定位LCA,而不需要像在普通二叉树中那样存储父节点或递归遍历整个树。

相关题目

235. 二叉搜索树的最近公共祖先

视频讲解

二叉搜索树找祖先

重点分析

方法一:递归

def lowestCommonAncestor(root, p, q):
    if p.val > root.val and q.val > root.val:
        return lowestCommonAncestor(root.right, p, q)
    if p.val < root.val and q.val < root.val:
        return lowestCommonAncestor(root.left, p, q)
    return root

在这里插入图片描述

方法二:迭代法

def lowestCommonAncestor(root, p, q):
    while root:
        if p.val < root.val and q.val < root.val:
            root = root.left
        elif p.val > root.val and q.val > root.val:
            root = root.right
        else:
            return root

  • 31
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值