力扣刷題(python)50天——第四十四天:二叉搜索樹的最近公共祖先
題目描述
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
方法
拿到題後感覺雖然做了很多題了,有很多想法,但是還是沒有想出解法,參考:
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/solution/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian–2/
後發現,之前二叉搜索樹的性質我沒有理解透徹,二叉搜索樹的大於小於對於左右樹枝是永久性的。
解答
# 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
"""
root_val=root.val
p_val=p.val
q_val=q.val
if p_val>root_val and q_val>root_val:
self.lowestCommonAncestor(root.right, p, q)
elif p_val<root_val and q_val<root_val:
self.lowestCommonAncestor(root.left, p, q)
else:
self.ans=root
return self.ans