652-Find Duplicate Subtrees

kevin聰發表於2018-05-25

Description

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 list.


問題描述

給定二叉樹, 返回所有重複子樹。對於每類重複子樹, 只需要返回任意一個子樹的根節點。

兩棵樹如何結構相同且所有對應節點的值相等, 那麼這兩棵樹重複。


問題分析

後序遍歷, 通過字串表示一棵樹, 通過map儲存字串對應個數, 若個數大於1, 說明此樹重複, 可以新增入結果中


解法

class Solution {
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        HashMap<String, Integer> map = new HashMap();
        List<TreeNode> res = new ArrayList();
        helper(root, map, res);
        return res;
    }
    private String helper(TreeNode root, HashMap<String, Integer> map, List<TreeNode> res){
        if(root == null) return "#";

        String temp = root.val + helper(root.left, map, res) + helper(root.right, map, res);
        if(!map.containsKey(temp)){
            map.put(temp,1);  
        }else{
            if(map.get(temp) < 2){
                map.put(temp, 2);
                res.add(root);
            }
        }

        return temp;
    }
}

相關文章