日野弥生:勉強しよう

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

发表于2025年03月22日

#树 #二叉树 #深度优先搜索

后根遍历,自底而上的思路进行深度优先搜索。

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root or root == p or root == q:
            return root

        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)

        if left and right:  # 左右子树都找到了祖先,则根节点是最近公共祖先
            return root
        elif left:  # 左子树找到了祖先
            return left
        else:  # 右子树找到了祖先,或者左右子树都没有找到
            return right  # 注意:这里需要返回 right,即使 right 为 None

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/

上一篇

LeetCode 215 - 数组中的第K个最大元素

下一篇

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