150强访谈中等

另一棵树的子树

“另一棵树的子树”问题的详细指南和 Python 实现。

问题陈述

中等

给定两个二叉树 root 和 subRoot 的根,如果 root 的子树具有相同的结构和 subRoot 的节点值,则返回 true,否则返回 false。

二叉树的子树是由树中的一个节点和该节点的所有后代组成的树。树也可以被视为其自身的子树。

这些树被表示为级别顺序列表。实现函数 isSubtree(root: list, subRoot: list) -> bool

约束条件
  • The number of nodes in the root tree is in the range [1, 2000]
  • The number of nodes in the subRoot tree is in the range [1, 1000]
  • -10000 <= root.val <= 10000
  • -10000 <= subRoot.val <= 10000

示例

Example 1
Input
[3,4,5,1,2], [4,1,2]
Output
True
Explanation

The subtree rooted at node 4 in the main tree matches subRoot exactly.

Example 2
Input
[3,4,5,1,2,None,None,None,None,0], [4,1,2]
Output
False
Explanation

The subtree rooted at 4 in the main tree has an extra node 0 under 2, so it doesn't match subRoot.

Need a Hint?
考虑使用树特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。