首页 > 其他分享 >LeetCode 1161. Maximum Level Sum of a Binary Tree

LeetCode 1161. Maximum Level Sum of a Binary Tree

时间:2024-03-20 10:46:18浏览次数:26  
标签:Binary TreeNode 1161 val level int sum Level null

原题链接在这里:https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/description/

题目:

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:

Input: root = [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.

Example 2:

Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output: 2

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -105 <= Node.val <= 105

题解:

Perforom level order traversal. And accumlate sum of each level.

When there is a new maximum, update the max and result level.

Time Complexity: O(n). n is number of nodes in the tree.

Space: O(n).

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     public int maxLevelSum(TreeNode root) {
18         if(root == null){
19             return 0;
20         }
21 
22         int max = Integer.MIN_VALUE;
23         int res = 0;
24         int level = 1;
25         LinkedList<TreeNode> que = new LinkedList<>();
26         que.add(root);
27         while(!que.isEmpty()){
28             int size = que.size();
29             int sum = 0;
30             while(size-- > 0){
31                 TreeNode cur = que.poll();
32                 sum += cur.val;
33                 if(cur.left != null){
34                     que.add(cur.left);
35                 }
36 
37                 if(cur.right != null){
38                     que.add(cur.right);
39                 }
40             }
41 
42             if(sum > max){
43                 max = sum;
44                 res = level;
45             }
46 
47             level++;
48         }
49 
50         return res;
51     }
52 }

 

标签:Binary,TreeNode,1161,val,level,int,sum,Level,null
From: https://www.cnblogs.com/Dylan-Java-NYC/p/18084720

相关文章

  • android_get_device_api_level
    {//ret=android_get_device_api_level();ret=28;} {intff_Build_SDK_INT(AVCodecContext*avctx){intret=-1;#if__ANDROID_API__>=24//android_get_device_api_level()isastaticinlinebeforeAPIlevel29.//dlsym()mightdoesn�......
  • 【算法】二分查找——BinarySearch
    一、概述二分查找又称折半查找,是一种能够大幅减少时间复杂度的查找方法,但是二分查找要求线性表必须词用顺序储存结构,而且表中元素按关键字有序排列。在后续讨论中,我们假设有序表递增有序。二分查找中使用的术语:目标Target——你要查找的值索引Index——你要查找的当前......
  • Binary Heap
    BinaryHeap一个基于concept的二叉堆板子实现。template<typenameTy,typenameCompare,typenameContainer=std::vector<Ty>>requiresrequires(Comparecomp,Tya,Tyb){std::is_same_v<bool,decltype(comp(a,b))>;}&&r......
  • Practical Learned Lossless JPEG Recompression with Multi-Level Cross-Channel Ent
    目录简介模型DCTCoefficientsRearrangement将系数重排Cross-ColorEntropyModelMatrixContextModelMulti-LevelCross-ChannelEntropyModel创新点实验设置训练数据集:测试数据集:训练细节:结果简介JPEG是一种非常流行的压缩方法,然而最近关于图像压缩的研究主要集中在未压......
  • Maven - 项目的JDK编译level是1.5,修改不掉??
    背景  idea中的maven项目,父项目和子项目的ProjectStructure的languagelevel都是1.5,怎么修改为8?尝试修改并应用后会失效,还是会自动恢复为1.5。 1、Settings中JavaCompiler中,子项目的Targetbytecodeversion都是1.52、ProjectStructure中的Module的LanguageLevel都是5......
  • B. Quasi Binary
    It'sasimpleproblemoncodeforces.wetraversethethroughthestringn,ifweencoutera'1',weaddanewstringtoansandsetstoptofalse.Otherwise,westoptheloop.Oncewefind1,wethenappendeither'1'or'0�......
  • Binary Tree Maximum Path Sum
    SourceGivenabinarytree,findthemaximumpathsum.Thepathmaystartandendatanynodeinthetree.ExampleGiventhebelowbinarytree,1/\23Return6.题解1-递归中仅返回子树路径长度题目很短,要求返回最大路径和。咋看一下......
  • CF1066E Binary Numbers AND Sum 题解
    分析因为\(a\)是一直没有改变的,移动的只有\(b\),所以从\(a\)的每一位的贡献入手。对于\(a\)中的从低到高第\(i\)位,其对应的十进制值是\(a_{n-i+1}\times2^{i-1}\)。注意到\(b\)是每次右移一位的,所以在\(b\)中能与\(a_{n-i+1}\)匹配的都是在下标区间\([1,m-i+1]......
  • 《Document-level Relation Extraction as Semantic Segmentation》论文阅读笔记
    原文代码摘要本文研究的是文档级关系抽取,即从文档中抽取出多个实体之间的关系。现有的方法主要是基于图或基于Transformer的模型,它们只考虑实体自身的信息,而忽略了关系三元组之间的全局信息。为了解决这个问题,本文提出了一种新的方法,它通过预测一个实体级关系矩阵来同时捕获局......
  • Go - Optimization - instruction-level parallelism (ILP)
      ......