150强访谈中等

相同的二叉树

“相同二叉树”问题的详细指南和 Python 实现。

问题陈述

中等

给定两个二叉树 p 和 q 的根,编写一个函数来检查它们是否相同。

如果两个二叉树结构相同并且节点具有相同的值,则认为它们是相同的。

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

约束条件
  • The number of nodes in both trees is in the range [0, 100]
  • -10000 <= Node.val <= 10000

示例

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

Both trees have the same structure and values.

Example 2
Input
[1,2], [1,None,2]
Output
False
Explanation

In the first tree, 2 is the left child. In the second tree, 2 is the right child. Different structures.

Example 3
Input
[1,2,1], [1,1,2]
Output
False
Explanation

Same structure but different values at the children.

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 资源

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