给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
例:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3
解释:节点 5 和节点 1 的最近公共祖先是节点 3 。
解析:
将找到节点或空节点,作为终止条件进行返回。对当前节点的左节点和有节点进行函数调用,若两个返回值都不为空,则代表当前节点为公共祖先。若只有一个不为空,则返回那个节点,
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root == p or root == q or root == None: # 终止条件,返回值要么为目标节点,要么为空
return root
left = self.lowestCommonAncestor(root.left, p, q) # 左子树的返回节点
right = self.lowestCommonAncestor(root.right, p, q) # 右子树的返回节点
if left != None and right != None: # 同时不为空则代表找到
return root
if left == None: # 返回不为空的那个,若同时为空则返回谁都一样
return right
return left
继续向上寻找。