leetcode_652. Find Duplicate Subtrees

来源:互联网 发布:seo关键词的布局原则 编辑:程序博客网 时间:2024/06/09 18:46

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


class Solution {    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {        List<TreeNode> res = new LinkedList<>();        pos(root,new HashMap<>(),res);        return res;            }    public String pos(TreeNode cur,Map<String,Integer> map,List<TreeNode> res){        if(cur == null)return "#";        String serial = cur.val + ","+pos(cur.left,map,res)+pos(cur.right,map,res);        if(map.getOrDefault(serial,0) == 1)            res.add(cur);        map.put(serial,map.getOrDefault(serial,0)+1);        return serial;    }}