⚡Flashcard Drill➔
NeetCode #436LC-652MediumTrees
← Back to All Problems

#436 · #652 · Find Duplicate Subtrees(寻找重复的子树)

📌 Problem Statement & Constraints

Given the root of a binary tree, return all duplicate subtrees: subtrees that occur more than once anywhere in the tree, with the same structure and values. Return the root of one representative per duplicate group. Constraints: the number of nodes is in [2, 5000], -200 <= Node.val <= 200.

💡 Core Algorithmic Approaches

  1. Serialise each subtree into a canonical string, then count how many times each string occurs.
  2. A post-order DFS builds the key as value,left_key,right_key; None becomes a fixed marker.
  3. The first time a key reaches a count of 2, record the node as a representative.
  4. The counting approach ensures each duplicate group is reported exactly once.

💻 Benchmark Python3 Implementation

class Solution:
    def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[TreeNode]:
        from collections import defaultdict
        cnt = defaultdict(int)
        res = []

        def dfs(node: Optional[TreeNode]) -> str:
            if not node:
                return "#"                 # null marker
            key = f"{node.val},{dfs(node.left)},{dfs(node.right)}"
            cnt[key] += 1
            if cnt[key] == 2:              # record exactly once per group
                res.append(node)
            return key

        dfs(root)
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n^2) worst case, because the serialised keys can be O(n) long each. Using interning (assigning each unique key an integer id) makes it O(n).
💾 Space Complexity
O(n^2) for the stored keys in the worst case, or O(n) with interning.

⚠️ Interview Pitfalls & Follow-ups

  • Appending on every occurrence after the first: the same subtree would be reported many times; the == 2 check is what deduplicates.
  • Omitting the null markers: different structures could produce the same serialisation.
  • Using a pre-order key: any consistent order works as long as it is applied uniformly; post-order is conventional.
  • Comparing subtrees structurally for every pair: O(n^3).
⚡
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

中文速览与面试要点

寻找重复的子树

给你一棵二叉树的根节点 root,返回所有 重复的子树 。对于同一类的重复子树,你只需要返回其中 任意一棵 的根结点即可。如果两棵树具有 相同的结构 和 相同的结点值 ,则认为二者是重复的。约束:树中的结点数在 [1, 5000] 范围内;-200 ≤ Node.val ≤ 200。

核心要点

  • 后序遍历 + 序列化子树(标准解) :对每个节点,用「节点值 + 左子树序列 + 右子树序列」构造该子树的唯一字符串标识,用哈希表统计出现次数。
  • 为什么必须后序 :子树的标识依赖左右子树的标识,必须自底向上构造。
  • 计数为 2 时加入结果 :只在第二次遇到同一标识时加入,避免重复添加。
  • 为什么空节点也要标记 :否则 [1,2] 与 [1,null,2] 会产生相同标识。
  • 优化 :用「子树 ID 编号」代替字符串,可把空间与时间降到 O(n)。

常见陷阱

  • 前序遍历构造标识 :也可以,但必须同时标记空节点;后序更自然。
  • 空节点不标记 :会产生误判(不同结构得到相同标识)。
  • 每次重复都加入结果 :应只在计数恰好为 2 时加入一次。
  • 用节点值作标识 :相同值的节点可能有不同子树,会误判。

参考实现

from collections import defaultdict

class Solution:
    def findDuplicateSubtrees(self, root: 'TreeNode') -> list:
        cnt = defaultdict(int)
        res = []

        def dfs(node) -> str:
            if not node:
                return '#'                  # 空节点标记
            key = f'{node.val},{dfs(node.left)},{dfs(node.right)}'
            cnt[key] += 1
            if cnt[key] == 2:               # 第二次出现 -> 加入结果
                res.append(node)
            return key

        dfs(root)
        return res