- [刷题防痴呆] 0652 - 寻找重复的子树 (Find Dup
- LeetCode | 0652. 寻找重复的子树【Python】
- [刷题防痴呆] 0564 - 寻找最近的回文数 (Find th
- [刷题防痴呆] 0609 - 在系统中查找重复文件 (Find
- Leetcode-652 寻找重复的子树
- [刷题防痴呆] 0389 - 找不同 (Find the Dif
- [刷题防痴呆] 0187 - 重复的DNA序列 (Repeate
- [刷题防痴呆] 0316 - 去除重复字母 (Remove Du
- [刷题防痴呆] 0217 - 存在重复元素 (Contains
- [刷题防痴呆] 0220 - 存在重复元素III (Contai
题目地址
https://leetcode.com/problems/find-duplicate-subtrees/
题目描述
652. Find Duplicate Subtrees
Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Example 1:
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
Example 2:
Input: root = [2,1,1]
Output: [[1]]
Example 3:
Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]
思路
- 二叉树的序列化, 前序或者后序都可以.
- 如果当前子树已经在map中出现一次, 则将其加入到res中.
- 之后当前子树如果再次出现, 则不加入到res.
关键点
代码
- 语言支持:Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Map<String, Integer> map = new HashMap<>();
List<TreeNode> res = new ArrayList<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
traverse(root);
return new ArrayList<>(res);
}
private String traverse(TreeNode node) {
if (node == null) {
return "#";
}
String left = traverse(node.left);
String right = traverse(node.right);
String str = node.val + "," + left + "," + right;
int count = map.getOrDefault(str, 0);
if (count == 1) {
res.add(node);
}
map.put(str, count + 1);
return str;
}
}
网友评论