236. Lowest Common Ancestor of a Binary Tree

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

solution

  • 后续遍历,自底向上的回溯。

  • 沿着树递归,注意如何最终返回最近公共祖先

  • 理解递归终止单个的返回,与数多分支处理的返回

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

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

        if l and r:
            return root
        if l:
            return l
        if r:
            return r

时间复杂度:O(h) 空间复杂度:O(h)

  • 迭代 iteration

  • 返回两个目标node之间的路‍‌径

    • 分别求从LCA到两个node之间的路径,然后merge

follow up

tree node 可以直接call parent or child

*1644. Lowest Common Ancestor of a Binary Tree II

*1650. Lowest Common Ancestor of a Binary Tree III

时间复杂度:O(h) 空间复杂度:O(1)

  • 迭代

*1676. Lowest Common Ancestor of a Binary Tree IV

1123. Lowest Common Ancestor of Deepest Leaves

2096. Step-By-Step Directions From a Binary Tree Node to Another

Last updated