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.

分析:把每个node当成root,然后得到它的preorder traversal string, 因为子node的preorder traversal string是可以被用在parent上的,这样时间复杂度只是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 }

 

posted @ 2019-07-04 03:06  北叶青藤  阅读(180)  评论(0编辑  收藏  举报