题目链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
难度:中等
描述:
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p
、q
,最近公共祖先表示为一个节点 x
,满足 x
是 p
、q
的祖先且 x
的深度尽可能大(一个节点也可以是它自己的祖先)。”
提示:p
,q
必在二叉树中且p != q
题解
# 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 is None:
return None
if p == root or q == root:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
# 没有找到p, q
if left is None and right is None:
return None
# p, q都在右子树中
if left is None:
return right
# p, q都在左子树中
if right is None:
return left
# p, q分别在左右子树中
return root