package com.算法专练.力扣.寻找重复的子树;
import java.util.*;
/**
* @author xnl
* @Description:
* @date: 2022/9/5 23:14
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode node = new TreeNode(1, new TreeNode(2, new TreeNode(4), null),
new TreeNode(3, new TreeNode(2, new TreeNode(4), null), new TreeNode(4)));
System.out.println(solution.findDuplicateSubtrees(node));
}
/**
* 使用hash,序列化字符串
* @param root
* @return
*/
Map<String,TreeNode> map = new HashMap<>();
Set<TreeNode> set = new HashSet<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
dfs(root);
return new ArrayList<>(set);
}
private String dfs(TreeNode node){
if (node == null){
return "";
}
StringBuilder sb = new StringBuilder();
sb.append(node.val);
sb.append("(");
sb.append(dfs(node.left));
sb.append(")(");
sb.append(dfs(node.right));
sb.append(")");
String serial = sb.toString();
if (map.containsKey(serial)){
set.add(map.get(serial));
} else {
map.put(serial, node);
}
return serial;
}
}
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;
}
}
力扣:652. 寻找重复的子树
于 2022-09-05 23:48:25 首次发布