1161 最大层内元素之和

其中 最小 的那个。

 

示例:

输入:[1,7,0,7,-8,null,null]
输出:2
解释:
第 1 层各元素之和为 1,
第 2 层各元素之和为 7 + 0 = 7,
第 3 层各元素之和为 7 + -8 = -1,
所以我们返回第 2 层的层号,它的层内元素之和最大。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-level-sum-of-a-binary-tree
 

本题较为容易,只要注意每次递归时层数加1

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int[] count;
    public Solution(){
            count = new int[100000];
    }
    public int maxLevelSum(TreeNode root) {
        Solution solution = new Solution();
         solution.func1(1,root);
         return solution.func2();
    }
    public void func1(int n,TreeNode root){
        if(root!=null){
        count[n]+=root.val;
        func1(n+1,root.left);
        func1(n+1,root.right);
    }
    }

    public int func2(){
        int max=1;
        for(int i =1 ; i<100000;i++){
            if(count[max]<count[i]) max = i;
        }
        return max;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值