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
652. Find Duplicate Subtrees
猜你喜欢
转载自www.cnblogs.com/tobeabetterpig/p/9920299.html
今日推荐
周排行