lc236. 二叉树的最近公共祖先 python题解

679 阅读1分钟

题目描述:

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

image.png

题解思路:

以root为根节点,该根节点下是否存在p或者q,只要存在一个,返回true 引入辅助函数helper(root,p,q)返回以root为根节点,是否包含p或者q的结果 L = helper(root.left,p,q) :左孩子包含p或者q的情况 R = helper(root.right,p,q) :左孩子包含p或者q的情况

L,R均为true,说明最近公共祖先是root

image.png

L,R有一个是true,且其父节点root==p or root==q,说明最近公共祖先是root

image.png

代码参考

# 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':
        self.ans = root
        self.helper(root,p,q)
        return self.ans
    def helper(self,root,p,q):
        if root is None:
            return False
        L = self.helper(root.left,p,q)
        R = self.helper(root.right,p,q)
        if L and R:
            self.ans = root
        if ( L or R ) and (root == p or root == q):
            self.ans = root
        return L or R or p == root or q == root