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返回的,反之依然。
python 复制代码
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。

方法二:递归法

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

python 复制代码
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,你的方法都会遍历整棵树来找到它们的所有父节点。这意味着树被遍历了两次。此外,对于找到的每对父节点,你使用了双层循环来比较它们,这会导致效率低下,尤其是在大树上。

方法三:迭代法

python 复制代码
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. 二叉搜索树的最近公共祖先

视频讲解

二叉搜索树找祖先

重点分析

方法一:递归

python 复制代码
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

方法二:迭代法

python 复制代码
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
相关推荐
mmmmath_32 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z3 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
Patrick在香港3 小时前
Claude Prompt 香港场景:公文里「今日」落在 6 个日历日上,「翌日」锚错了 5 天
python·自然语言处理·正则表达式·claude·数据清洗
YsyaaabB3 小时前
Python 数值分析
python
阿洛学长3 小时前
计算机二级 Python 基本操作题(15 分)真题笔记(0101 ~ 1903 全套)
python·pycharm
君顾13 小时前
上海24小时自助健身房系统开发实战指南:从架构设计到落地部署
java·开发语言·健身房
醇氧4 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
weixin199701080164 小时前
[特殊字符]️《二手ERP对接电商平台的总体方案:统一数据模型 + 事件驱动 + 灰度上线6原则》(附Python源码)
大数据·python
大熊背4 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温