算法题目 21周 Maximum Level Sum of a Binary Tree

288 阅读1分钟

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:

image

**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:**

1.  The number of nodes in the given tree is between `1` and `10^4`.
2.  `-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.