LeetCode 题解工作台

另一棵树的子树

给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在,返回 true ;否则,返回 false 。 二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。 tree 也可以看做它自身的一棵子树。 …

category

5

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 二分·树·traversal

bolt

答案摘要

我们定义一个辅助函数 $\textit{same}(p, q)$,用于判断以 为根节点的树和以 为根节点的树是否相等。如果两棵树的根节点的值相等,并且它们的左子树和右子树也分别相等,那么这两棵树是相等的。 在 $\textit{isSubtree}(\textit{root}, \textit{subRoot})$ 函数中,我们首先判断 是否为空,如果为空,则返回 。否则,我们判断 和 …

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两棵二叉树 rootsubRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在,返回 true ;否则,返回 false

二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。

 

示例 1:

输入:root = [3,4,5,1,2], subRoot = [4,1,2]
输出:true

示例 2:

输入:root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
输出:false

 

提示:

  • root 树上的节点数量范围是 [1, 2000]
  • subRoot 树上的节点数量范围是 [1, 1000]
  • -104 <= root.val <= 104
  • -104 <= subRoot.val <= 104
lightbulb

解题思路

方法一:DFS

我们定义一个辅助函数 same(p,q)\textit{same}(p, q),用于判断以 pp 为根节点的树和以 qq 为根节点的树是否相等。如果两棵树的根节点的值相等,并且它们的左子树和右子树也分别相等,那么这两棵树是相等的。

isSubtree(root,subRoot)\textit{isSubtree}(\textit{root}, \textit{subRoot}) 函数中,我们首先判断 root\textit{root} 是否为空,如果为空,则返回 false\text{false}。否则,我们判断 root\textit{root}subRoot\textit{subRoot} 是否相等,如果相等,则返回 true\text{true}。否则,我们递归地判断 root\textit{root} 的左子树和右子树是否包含 subRoot\textit{subRoot}

时间复杂度 O(n×m)O(n \times m),空间复杂度 O(n)O(n)。其中 nnmm 分别是树 rootroot 和树 subRootsubRoot 的节点个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        def same(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
            if p is None or q is None:
                return p is q
            return p.val == q.val and same(p.left, q.left) and same(p.right, q.right)

        if root is None:
            return False
        return (
            same(root, subRoot)
            or self.isSubtree(root.left, subRoot)
            or self.isSubtree(root.right, subRoot)
        )
speed

复杂度分析

指标
时间complexity can reach O(m*n) in the worst case for comparing m nodes in root with n nodes in subRoot, but hashing or pruning identical subtrees can reduce comparisons. Space complexity depends on recursion stack depth or storage for subtree hashes.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Asks whether recursion or iterative traversal is preferable for subtree comparison.

  • question_mark

    Checks if null node handling is correctly implemented in the DFS solution.

  • question_mark

    Mentions optimization using subtree serialization or hashing techniques.

warning

常见陷阱

外企场景
  • error

    Failing to check both left and right children for exact match leading to false positives.

  • error

    Confusing a node with identical value as a valid subtree without matching the full structure.

  • error

    Exceeding recursion limits on deeply nested trees without iterative fallback.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Determine if a tree is a mirror subtree of another, requiring reversed child comparisons.

  • arrow_right_alt

    Count the total number of occurrences where subRoot appears as a subtree within root.

  • arrow_right_alt

    Check if subRoot appears as a subtree in a forest of multiple disconnected trees.

help

常见问题

外企场景

另一棵树的子树题解:二分·树·traversal | LeetCode #572 简单