Given the root
of a binary tree, the level of its root is 1
, the level of its children is 2
, and so on.
Return the smallest level X
such that the sum of all the values of nodes at level X
is maximal.
Example 1:
<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 13px; margin-top: 0px; margin-bottom: 1em; overflow: auto; background: rgb(247, 249, 250); padding: 10px 15px; color: rgb(38, 50, 56); line-height: 1.6; border-radius: 3px; white-space: pre-wrap; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">Input: [1,7,0,7,-8,null,null]
Output: 2
Explanation:
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.
Note:
- The number of nodes in the given tree is between
1
and10^4
. -10^5 <= node.val <= 10^5
暴力解法:
public int maxLevelSum(TreeNode root) {
int[] sum = new int[40];
int level = 0;
check(root,sum,level);
int retsum = 0;
int retlevel = 0;
for(int i=0;i<sum.length;i++){
if(retsum<sum[i]){
retsum = sum[i];
retlevel = i;
}
}
return retlevel+1;
}
public void check(TreeNode root,int[] sum,int level){
sum[level] = sum[level] +root.val;
if(root.left!=null){
check(root.left,sum,level+1);
}
if(root.right!=null){
check(root.right,sum,level+1);
}
}
目前題目提交的人還是太少了盒让,只有6千多通過荆忍,暴力都通過实苞。
Runtime: 3 ms, faster than 100.00% of Java online submissions for Maximum Level Sum of a Binary Tree.
Memory Usage: 41.3 MB, less than 100.00% of Java online submissions for Maximum Level Sum of a Binary Tree.