#题目内容
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)
例如,给定如下二叉树: root =【3,5,1,6,2,0,8,null,null,7,4】
#解题思路
先深度遍历左子树,再遍历右子树,回溯时判断是否找到q,p
找到时返回1,当一个节点的值等于2时,就返回该节点,其就
是q和p的最近公共祖先。
class Solution:
def __init__(self):
self.target = None
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q:
'TreeNode') -> 'TreeNode':
def recurse_tree(current_node):
if not current_node:
return False
left = recurse_tree(current_node.left)
right = recurse_tree(current_node.right)
mid = current_node == q or current_node == p
if mid + left + right == 2:
self.target = current_node
return mid or left or right
recurse_tree(root)
return self.target