?LeetCode刷題實戰(zhàn)235:二叉搜索樹的最近公共祖先
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).”

示例
示例 1:
輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
輸出: 6
解釋: 節(jié)點 2 和節(jié)點 8 的最近公共祖先是 6。
示例 2:
輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
輸出: 2
解釋: 節(jié)點 2 和節(jié)點 4 的最近公共祖先是 2, 因為根據(jù)定義最近公共祖先節(jié)點可以為節(jié)點本身。
說明:
所有節(jié)點的值都是唯一的。
p、q 為不同節(jié)點且均存在于給定的二叉搜索樹中。
解題
如果兩個節(jié)點值都小于根節(jié)點,說明他們都在根節(jié)點的左子樹上,我們往左子樹上找
如果兩個節(jié)點值都大于根節(jié)點,說明他們都在根節(jié)點的右子樹上,我們往右子樹上找
如果一個節(jié)點值大于根節(jié)點,一個節(jié)點值小于根節(jié)點,說明他們他們一個在根節(jié)點的左子樹上一個在根節(jié)點的右子樹上,那么根節(jié)點就是他們的最近公共祖先節(jié)點。
遞歸法
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
elif root.val > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
else:
return root
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
while root:
if root.val > max(p.val, q.val):
root = root.left
elif root.val < min(p.val, q.val):
root = root.right
else:
return root
return root
LeetCode刷題實戰(zhàn)222:完全二叉樹的節(jié)點個數(shù)
LeetCode刷題實戰(zhàn)225:用隊列實現(xiàn)棧
LeetCode刷題實戰(zhàn)226:翻轉(zhuǎn)二叉樹
LeetCode刷題實戰(zhàn)227:基本計算器 II
LeetCode刷題實戰(zhàn)228:匯總區(qū)間
LeetCode刷題實戰(zhàn)229:求眾數(shù) II
LeetCode刷題實戰(zhàn)230:二叉搜索樹中第K小的元素
LeetCode刷題實戰(zhàn)232:用棧實現(xiàn)隊列
LeetCode刷題實戰(zhàn)233:數(shù)字 1 的個數(shù)
