LC 652. 寻找重复的子树

题目描述

这是 LeetCode 上的 652. 寻找重复的子树 ,难度为 中等

给定一棵二叉树 root,返回所有重复的子树。

对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。

如果两棵树具有相同的结构和相同的结点值,则它们是重复的。

示例 1:

1
2
3
输入:root = [1,2,3,4,null,2,4,null,null,4]

输出:[[2,4],[4]]

示例 2:

1
2
3
输入:root = [2,1,1]

输出:[[1]]

示例 3:

1
2
3
输入:root = [2,2,2,3,null,3,null]

输出:[[2,3],[3]]

提示:

  • 树中的结点数在 $[1,10^4]$ 范围内。
  • $-200 <= Node.val <= 200$

DFS + 哈希表

设计递归函数 String dfs(TreeNode root),含义为返回以传入参数 root 为根节点的子树所对应的指纹标识。

对于标识的设计只需使用 "_" 分割不同的节点值,同时对空节点进行保留(定义为空串 " ")即可。

使用哈希表记录每个标识(子树)出现次数,当出现次数为 $2$(首次判定为重复出现)时,将该节点加入答案。

Java 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
Map<String, Integer> map = new HashMap<>();
List<TreeNode> ans = new ArrayList<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
dfs(root);
return ans;
}
String dfs(TreeNode root) {
if (root == null) return " ";
StringBuilder sb = new StringBuilder();
sb.append(root.val).append("_");
sb.append(dfs(root.left)).append(dfs(root.right));
String key = sb.toString();
map.put(key, map.getOrDefault(key, 0) + 1);
if (map.get(key) == 2) ans.add(root);
return key;
}
}

Typescript 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let ans: Array<TreeNode>
let map: Map<string, number>
function findDuplicateSubtrees(root: TreeNode | null): Array<TreeNode | null> {
ans = new Array<TreeNode>()
map = new Map<string, number>()
dfs(root)
return ans
};
function dfs(root: TreeNode | null): string {
if (root == null) return " "
let key = root.val + "_"
key += dfs(root.left)
key += dfs(root.right)
if (!map.has(key)) map.set(key, 1)
else map.set(key, map.get(key) + 1)
if (map.get(key) == 2) ans.push(root)
return key
}

  • 时间复杂度:DFS 过程复杂度为 $O(n)$,对于每个子树需要构造出与子树同等规模的字符串,复杂度为 $O(n)$。整体复杂度为 $O(n^2)$
  • 空间复杂度:$O(n)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.652 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。