LeetCode 508. Most Frequent Subtree Sum

508. Most Frequent Subtree Sum

Description Submission Solutions

  • Total Accepted: 4007
  • Total Submissions: 7684
  • Difficulty: Medium
  • Contributors: Cyber233

 

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.

Subscribe to see which companies asked this question.

【题目分析】

给定一颗二叉树,求出以任意一个节点为根节点的子树的和,然后返回出现频率最高的和值。

【思路】

用递归的方法求出每一个根节点对应的子树的和值,并且把它们保存在HashMap中,统计map中出现频率最高的值,并把它们返回。

【java代码】

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

 

posted @ 2017-02-20 14:20  Black_Knight  阅读(1066)  评论(0编辑  收藏  举报