题目
思路
解题的关键是知道自顶向低递归遍历,第一次遇到root在p和q的区间中时,则root就是p和q的最近公共祖先节点。
递归法
# 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':
if not root:
return
if root.val>p.val and root.val>q.val:
left = self.lowestCommonAncestor(root.left, p, q)
if left:
return left
if root.val<p.val and root.val<q.val:
right = self.lowestCommonAncestor(root.right, p, q)
if right:
return right
return root
迭代法
# 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':
while root:
if root.val>p.val and root.val>q.val:
root = root.left
elif root.val<p.val and root.val<q.val:
root = root.right
else:
return root