https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
递归方法
# 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 None
if root==q or root==p:
return root#如果节点为目标地址,则返回该节点
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)
if left and right:
return root#如果节点在左和右都有目标值,则该节点为最近祖先
return left if left else right