Lowest Common Ancestor of a Binary Tree 最近共同祖先問題

235, 236 的做法完全一模一樣。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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

1650 差在要先找出 Root 在哪

上面只是示範可以用前面的程式碼繼續來完成, 1650. 可以更簡單的在搜尋父節點時就找到最近共同祖先。

這個系列只有第二道題目 1644 需要小心一點而已,因為題目給定的 p 、 q 可能不在樹裡面。但是做法完全可以一樣,只差在要多紀錄所有走訪過的點。

後序遍歷

Last updated