1. 程式人生 > >【LeetCode 簡單題】64-二叉搜尋樹的最近公共祖先

【LeetCode 簡單題】64-二叉搜尋樹的最近公共祖先

宣告:

今天是第64道題。給定一個二叉搜尋樹, 找到該樹中兩個指定節點的最近公共祖先。以下所有程式碼經過樓主驗證都能在LeetCode上執行成功,程式碼也是借鑑別人的,在文末會附上參考的部落格連結,如果侵犯了博主的相關權益,請聯絡我刪除

(手動比心ღ( ´・ᴗ・` ))

正文

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

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

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

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         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 為不同節點且均存在於給定的二叉搜尋樹中。

解法1。審題得知這是1棵二叉搜尋樹,意味著比當前節點大的元素在右邊,小的在左邊所以給定p、q,只需遍歷左右子樹找到介於這兩者之間(閉區間)的元素即可,程式碼如下。

執行用時: 112 ms, 在Lowest Common Ancestor of a Binary Search Tree的Python提交中擊敗了29.72% 的使用者

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

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        min_ele = min(p,q)
        max_ele = max(p,q)

        if root.val >= min_ele and root.val <= max_ele:
            return root
        else:
            l = self.lowestCommonAncestor(root.left,p,q)
            r = slef.lowestCommonAncestor(root.right,p,q)
            
            if l:
                return l
            if r:
                return r
        

解法2。分別用給定的p、q這2個值逐一遍歷比較二叉樹的節點元素直到索引到自身,順便用容器stack存放比較過的元素值(包括自身),遍歷stack,如果遇到不相等的元素(就是p、q)就返回上一個節點(就是父節點),遍歷完了就返回stack最後一個元素,程式碼如下。

執行用時: 96 ms, 在Lowest Common Ancestor of a Binary Search Tree的Python提交中擊敗了61.29% 的使用者

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

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        s_p = []
        s_q = []
        self.search(root,p,s_p)
        self.search(root,q,s_q)
        
        n = min(len(s_p),len(s_q))
        for i in range(n):
            if s_p[i] != s_q[i]
                return s_q[i-1]
        return s_q[n-1]


    def search(self,root,x,stack):
        stack.append(root)
        if root.val < x.val:
            self.search(root.right, x, stack)
        elif root.val > x.val:
            self.search(root.left, x, stack)
        else:
            return

結尾

解法1:https://blog.csdn.net/qq_34364995/article/details/80657907

解法2:LeetCode