算法題目-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千多通過(guò),暴力都通過(guò)。
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.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容