1. 程式人生 > 實用技巧 >Leetcode 235 Lowest Common Ancestor of a Binary Search Tree

Leetcode 235 Lowest Common Ancestor of a Binary Search Tree

題目介紹

在二叉查詢樹中,查詢給定兩個不同節點的最近的公共父節點(節點可以當做自己的父節點)。

Examples:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Solutions

因為是二叉查詢樹,所以特點有任意節點都大於其左子樹,小於其右子樹。兩個節點的分佈可以有兩種情況:

  1. 兩個節點都在左子樹或者右子樹
  2. 兩個節點分別為在某個節點的左子樹和右子樹上

對於情況一,必有一個節點為公共父節點,則公共父節點為最先找到的節點。對於情況二,公共父節點為當前父節點。

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if p.val < root.val and q.val < root.val:
            return self.lowestCommonAncestor(root.left, p, q)
        elif p.val > root.val and q.val > root.val:
            return self.lowestCommonAncestor(root.right, p, q)
        else:
            return root

延伸

對應的還有Leetcode 236 Lowest Common Ancestor of a Binary Tree

這題不同的地方在於,並不是二叉查詢樹,所以不能根據值的大小來進行判斷。但是仍然可以利用遞迴的思想,每次查詢都返回公共父節點:

  • 分別在當前節點的左子樹和右子樹中進行查詢
    • 如果當前節點的左右子樹都有返回值,說明它們都查詢到自己作為公共父節點,因此公共父節點應該為當前節點
    • 如果只有一個子樹有返回值,說明兩個節點都在一個子樹中
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if not root or p.val == root.val or q.val == root.val:
            return root
        if root:
            left_res = self.lowestCommonAncestor(root.left, p, q)
            right_res = self.lowestCommonAncestor(root.right, p, q)
            
            if left_res and right_res:
                return root
            return left_res or right_res