給定一個二叉搜索樹, 找到該樹中兩個指定節點的最近公共祖先。web
利用BST的性質,若是該結點小於給定的其中一個結點,而且大於另一個給定的結點,那麼則認爲該點是兩個結點的最近公共祖先;ide
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)
return root
def lowestCommonAncestor(self, root, p, q):
"""
迭代實現
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
while root:
if p.val < root.val and q.val < root.val:
root = root.left
elif p.val > root.val and q.val > root.val:
root = root.right
else:
return root