652.Find Duplicate Subtrees
发布时间:2020-12-14 04:15:35 所属栏目:大数据 来源:网络整理
导读: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 /
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. https://www.youtube.com/watch?v=JLK92dbTt8k https://leetcode.com/problems/find-duplicate-subtrees/solution/ Time n * n class Solution { Map<String,Integer> map; List<TreeNode> res; public List<TreeNode> findDuplicateSubtrees(TreeNode root) { map = new HashMap<>(); res = new ArrayList<>(); helper(root); return res; } private String helper(TreeNode node){ if(node == null) return "#"; String serial = node.val + "," + helper(node.left) + "," + helper(node.right); map.put(serial,map.getOrDefault(serial,0) + 1); if(map.get(serial) == 2) res.add(node); return serial; } } Solution 2 : time (N) computeIfAbsent() ? class Solution { int t; Map<String,Integer> trees; Map<Integer,Integer> count; List<TreeNode> ans; public List<TreeNode> findDuplicateSubtrees(TreeNode root) { t = 1; trees = new HashMap(); count = new HashMap(); ans = new ArrayList(); lookup(root); return ans; } public int lookup(TreeNode node) { if (node == null) return 0; String serial = node.val + "," + lookup(node.left) + "," + lookup(node.right); int uid = trees.computeIfAbsent(serial,x-> t++); count.put(uid,count.getOrDefault(uid,0) + 1); if (count.get(uid) == 2) ans.add(node); return uid; } } What is the difference between putIfAbsent and computeIfAbsent in Java 8 Map ? https://stackoverflow.com/questions/48183999/what-is-the-difference-between-putifabsent-and-computeifabsent-in-java-8-map (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |