⚡Flashcard Drill➔
NeetCode #390LC-100EasyTreesBlind 75NC 150NC 250
← Back to All Problems

#390 · #100 · Same Tree(相同的树)

📌 Problem Statement & Constraints

Given the roots of two binary trees p and q, return true if they are structurally identical and every corresponding node has the same value. Constraints: the number of nodes in each tree is in [0, 100].

💡 Core Algorithmic Approaches

  1. Compare the roots recursively: both None means equal, exactly one None means unequal.
  2. If both exist, the values must match and both subtrees must match.
  3. The base cases must be checked in the order both None then either None, otherwise a None would be dereferenced.
  4. The recursion visits at most the smaller tree in full.

💻 Benchmark Python3 Implementation

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q:
            return True                    # both empty -> equal
        if not p or not q:
            return False                   # exactly one empty -> unequal
        return (p.val == q.val
                and self.isSameTree(p.left, q.left)
                and self.isSameTree(p.right, q.right))

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(min(m, n)): the recursion stops as soon as a mismatch is found.
💾 Space Complexity
O(h) for the recursion stack.

⚠️ Interview Pitfalls & Follow-ups

  • Checking p.val == q.val before the None cases: a None would raise an AttributeError.
  • Using p.val == q.val alone: the structure would not be verified, so a node with an extra child would pass.
  • Comparing only the left subtrees: both sides must be checked.
  • Assuming the trees have equal size: they may differ, which the either None case catches.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

相同的树

给你两棵二叉树的根节点 p 和 q,编写一个函数来检验这两棵树是否相同。如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。约束:两棵树上的节点数目都在范围 [0, 100] 内;-10^4 ≤ Node.val ≤ 10^4。

核心要点

  • 递归同时遍历(标准解) :同时递归两棵树的对应位置,比较值与结构。
  • 三种情况 :都为空 → 相同;只有一个为空 → 不同;都非空 → 比较值并递归左右子树。
  • 顺序不能颠倒 :必须先判断「都为空」再判断「只有一个为空」,否则会把「都为空」误判为不同。
  • 复杂度 :O(min(m, n)),一旦发现不同立即返回。

常见陷阱

  • 只比较值不比较结构 :如 p = [1,2] 、 q = [1,null,2] 中序遍历结果相同但结构不同。必须同时递归左右子树。
  • 两个判断的顺序颠倒 :先写 if not p or not q: return False 会把「都为空」的情况误判为不同。必须先判断「都为空」。
  • 用中序遍历结果比较 :不同结构的树可能有相同的中序遍历(如上例),不能作为判据。

参考实现

class Solution:
    def isSameTree(self, p: 'TreeNode', q: 'TreeNode') -> bool:
        if not p and not q:             # 都为空 -> 相同
            return True
        if not p or not q:              # 只有一个为空 -> 不同
            return False
        return (p.val == q.val
                and self.isSameTree(p.left, q.left)
                and self.isSameTree(p.right, q.right))