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]]
思路: 既然是树就要考虑到遍历,其次考虑是前中后哪种遍历,在判断当前节点时要知道我的子节点都长什么样,这就说明是后序遍历,但是我现在只知道我当前节点及其子节点长什么样了,如何知道其他节点及其子节点长什么样呢?我们可以将各个节点及子节点的状态保存在一个map中,进行判断,重复的话就添加到LinkedList中。
public class FindDuplicatSubtrees {
Map<String,Integer> map = new HashMap<>();
List<TreeNode> ans = new LinkedList<>();
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
traverse(root);
return ans;
}
public String traverse(TreeNode node){
if(node == null)return "#";
String left = traverse(node.left);
String right = traverse(node.right);
//将node的左右子树都序列化掉
String subTree = left + "," + right + "," + node.val;
int frequent = map.getOrDefault(subTree,0);
if (frequent == 1){
ans.add(node);
}
map.put(subTree,frequent + 1);
return subTree;
}
}