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

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

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

  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.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容