# 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 root==p or root==q or root==None:#如果结点是p或者q,只需要结点的左或右子树包含q或者p,这时root就是公共祖先。或者空姐点,说明到了递归的终止条件。
return root
#判断左右子树是否分别包含p,q
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)
if left and right:#异侧时,root为公共祖先
return root
elif left and not right:#都在左子树或者其中一个在左子树另一个就是root。
return left
elif not left and right:#同上
return right
else:
return None
'''公共祖先,该结点左子树是p右子树是q,或者左子树是q,右子树,或者p==root,或者q==root。
要自下而上的寻找,肯定是后序。
'''
235递归,注意利用搜索树的特性
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root.val>p.val and root.val>q.val:
return self.lowestCommonAncestor(root.left,p,q)
elif root.val<p.val and root.val<q.val:
return self.lowestCommonAncestor(root.right,p,q)
else:
return root
迭代
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.righ
else:
return root
return None