LeetCode-1161. Maximum Level Sum of a Binary Tree

这篇博客介绍了LeetCode的第1161题——Maximum Level Sum of a Binary Tree。文章阐述了如何解决这个二叉树层次遍历的变种问题,包括解题思路、算法描述和Java代码实现,并展示了运行结果。

LeetCode-1161. Maximum Level Sum of a Binary Tree

  • 原题链接:https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/

解题思路

  • 其实就是二叉树的层次遍历的变种而已,二叉树层次遍历应该都很熟悉了,就不多说了

算法描述

  • Step1:如果根节点root为空,返回0
  • Step2:如果不为空,把root放入队列了,初始化最大值为root的数据值,数据和最大的层数初始化为1
  • Step3:然后按照二叉树层次遍历,计算每层数据和,和记录的最大值作比较,如果比已记录的最大值还要大,就更新最大值和最大值所在的层数
  • Step4:最后返回最大值所在层数

代码实现-Java

class Solution {
    public int maxLevelSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int maxLevel=1, curLevel = 0;
        int max = root.val;
        int sum = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            curLevel++;
            sum = 0;
            for(int i=0;i<size;i++){
                TreeNode tmp = queue.poll();
                sum += tmp.val;
                if(tmp.left != null){
                    queue.offer(tmp.left);
                }
                if(tmp.right != null){
                    queue.offer(tmp.right);
                }
            }
            if(sum > max){
                max = sum;
                maxLevel = curLevel;
            }
        }
        return maxLevel;
    }
}

运行结果数据

Runtime: 9 ms, faster than 80.47% of Java online submissions for Maximum Level Sum of a Binary Tree. Memory Usage: 39.6 MB, less than 100.00% of Java online submissions for Maximum Level Sum of a Binary Tree.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值