# 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:
#函数用来寻找p或q
if not root: return
#如果p 或 q为根节点,直接返回,不用寻找
if root == p or root == q: return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
#在左子树和右子树中都找到,那么返回root
if left and right: return root
#p, q都在左子树,返回左子树找到的第一个节点,即为p和q的公共祖先
if left: return left
if right: return right
# 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
while root:
if p.val > root.val and q.val > root.val:
root = root.right
elif p.val < root.val and q.val < root.val:
root = root.left
else:
return root
'''
#递归
if not root: return
if p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
else:
return root
'''