Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any oneof them.
Two trees are duplicate if they have the same structure with same node values.
Example 1:
1 / \ 2 3 / / \ 4 2 4 / 4The following are two duplicate subtrees:
2 / 4and
4Therefore, you need to return above trees' root in the form of a list.
题意:
在一个二叉树中,寻找相同的子树,相同子树要有相同的结构和相同的节点的值。
思路:
最开始的思路是用纯粹的递归判断每个子树,但是这种解法会超时。
discuss中的高票答案提供的思路是将每一个节点的左右子树的value序列化,存储在hashmap中,这样就是判断string有没有相同的。
代码如下:
class Solution {
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
List<TreeNode> res = new LinkedList<>();
postorder(root, new HashMap<>(), res);
return res;
}
public String postorder(TreeNode cur, Map<String, Integer> map, List<TreeNode> res) {
if(cur == null)
return "#";
//将二叉树的信息转化为string
String serial = cur.val + "," + postorder(cur.left, map, res) + "," + postorder(cur.right, map, res);
//将节点加入list
if(map.getOrDefault(serial, 0) == 1)
res.add(cur);
//更新map
map.put(serial, map.getOrDefault(serial, 0) +1);
return serial;
}
}