[LeetCode] 508. Most Frequent Subtree Sum

Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

Examples 1
Input:

  5
 /  
2   -3

return [2, -3, 4], since all the values happen only once, return all of them in any order.

Examples 2
Input:

  5
 /  
2   -5

return [2], since 2 happens twice, however -5 only occur once.

Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

出现次数最多的子树元素和。

题意是给一棵二叉树,请输出树中出现次数最多的子树的和都是哪些。题意跟path sum类的题很接近,事实上做法也很接近,都是后序遍历的题。只不过在做后序遍历的同时需要用hashmap记录<每个不同的子树的和, 及其出现次数>。其他的都遵循后序遍历的逻辑做即可。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     HashMap<Integer, Integer> map = new HashMap<>();
18     int max = 0;
19     public int[] findFrequentTreeSum(TreeNode root) {
20         // corner case
21         if (root == null) {
22             return new int[0];
23         }
24 
25         // normal case
26         helper(root);
27         List<Integer> list = new ArrayList<>();
28         for (int i : map.keySet()) {
29             if (map.get(i) == max) {
30                 list.add(i);
31             }
32         }
33         int[] res = new int[list.size()];
34         for (int i = 0; i < res.length; i++) {
35             res[i] = list.get(i);
36         }
37         return res;
38     }
39 
40     private int helper(TreeNode root) {
41         if (root == null) {
42             return 0;
43         }
44         int left = helper(root.left);
45         int right = helper(root.right);
46         int sum = left + right + root.val;
47         map.put(sum, map.getOrDefault(sum, 0) + 1);
48         max = Math.max(max, map.get(sum));
49         return sum;
50     }
51 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13461489.html