题目描述
分析
要想找两个给定的节点的公共祖先,你首先得知道两个节点“大概”在哪里吧。为什么说是大概呢,应为你可以不用知道具体的位置,只要知道在左子树还是右子树基本就可以断定公共祖先了。如果当前节点的左子树有两个节点中的一个,右子树有两个节点中的一个,那当前节点不就是公共祖先了吗。本质上依然是一个前序遍历的改造。
代码
# 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==None:
return None
if root==p or root==q:
return root
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)
if left and right:
return root
if left==None and right==None:
return None
else:
if left:
return left
else:
return right