LeetCode236 二叉树的最近公共祖先

LeetCode236 二叉树的最近公共祖先

dfs二叉树,记录以当前节点为根节点的子树是否包含p节点或q节点

记录第一次满足条件的节点即为所求最近公共祖先

判断条件为:1. 左右子树分别含有p节点和q节点;2. 当前节点为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 __init__(self):
        self.ans = None

    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':

        def dfs(cur):
            
            if cur is None: return False

            lson = dfs(cur.left)
            rson = dfs(cur.right)

            if ((cur.val == p.val or cur.val == q.val) and (lson or rson)) or (lson and rson):
                if self.ans is None: self.ans = cur

            return lson or rson or cur.val == p.val or cur.val == q.val

        dfs(root)
        return self.ans

posted on 2022-07-02 16:28  solvit  阅读(14)  评论(0编辑  收藏  举报

导航