1. 程式人生 > 實用技巧 >LeetCode | 0235. 二叉搜尋樹的最近公共祖先【Python】

LeetCode | 0235. 二叉搜尋樹的最近公共祖先【Python】

Problem

LeetCode

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself

).”

Example 1:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-dGzMQij7-1610372086960)(https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png)]

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.

Example 2:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-KanePah3-1610372086969)(

https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png)]

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.

Example 3:

Input: root = [2,1], p = 2, q = 1
Output: 2

Constraints:

  • The number of nodes in the tree is in the range [2, 105].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • p != q
  • p and q will exist in the BST.

問題

力扣

給定一個二叉搜尋樹, 找到該樹中兩個指定節點的最近公共祖先。

百度百科中最近公共祖先的定義為:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。”

例如,給定如下二叉搜尋樹: root = [6,2,8,0,4,7,9,null,null,3,5]

示例 1:

輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
輸出: 6 
解釋: 節點 2 和節點 8 的最近公共祖先是 6。

示例 2:

輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
輸出: 2
解釋: 節點 2 和節點 4 的最近公共祖先是 2, 因為根據定義最近公共祖先節點可以為節點本身。

說明:

  • 所有節點的值都是唯一的。
  • p、q 為不同節點且均存在於給定的二叉搜尋樹中。

思路

遍歷

利用二叉搜尋樹的性質,中序遍歷就是遞增的順序。
於是,可以同時判斷 p、q 大小,看看都在左邊還是都在右邊還是左右都有。

Python3 程式碼

# 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':
        ancestor = root
        while True:
            # p q 在左邊
            if p.val < ancestor.val and q.val < ancestor.val:
                ancestor = ancestor.left
            # p q 在右邊
            elif p.val > ancestor.val and q.val > ancestor.val:
                ancestor = ancestor.right
            # p q 分別在左右,當前節點就是最近公共祖先
            else:
                break
        return ancestor

GitHub 連結

Python