Find Duplicate Subtrees

Given 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 same node values.

Example 1:

        1
       / \
      2   3
     /   / \
    4   2   4
       /
      4

The following are two duplicate subtrees:

      2
     /
    4

and

    4

Therefore, you need to return above trees' root in the form of a listn.

Analysis: for each node as the root, and then get its preorder traversal string, because the child node of the preorder traversal string can be used in the parent, but this time complexity O (n).

 1 class Solution {
 2     public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
 3         List<TreeNode> res = new LinkedList<>();
 4         preorder(root, new HashMap<>(), res);
 5         return res;
 6     }
 7 
 8     public String preorder(TreeNode cur, Map<String, Integer> map, List<TreeNode> res) {
 9         if (cur == null) return "#";  
10         String serial = cur.val + "," + preorder(cur.left, map, res) + "," + preorder(cur.right, map, res);
11         if (map.getOrDefault(serial, 0) == 1) res.add(cur);
12         map.put(serial, map.getOrDefault(serial, 0) + 1);
13         return serial;
14     }
15 }

 

Guess you like

Origin www.cnblogs.com/beiyeqingteng/p/11130065.html