|
| 1 | +--- |
| 2 | +id: maximum-level-sum-of-a-binary-tree |
| 3 | +title: Maximum Level Sum of a Binary Tree |
| 4 | +sidebar_label: 1161. Maximum Level Sum of a Binary Tree |
| 5 | +tags: |
| 6 | +- Tree |
| 7 | +- Breadth-First Search |
| 8 | +- Binary Tree |
| 9 | +description: "This is a solution to the Maximum Level Sum of a Binary Tree problem on LeetCode." |
| 10 | +--- |
| 11 | + |
| 12 | +## Problem Description |
| 13 | +Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. |
| 14 | + |
| 15 | +Return the smallest level x such that the sum of all the values of nodes at level x is maximal. |
| 16 | +### Examples |
| 17 | + |
| 18 | +**Example 1:** |
| 19 | + |
| 20 | +``` |
| 21 | +Input: root = [1,7,0,7,-8,null,null] |
| 22 | +Output: 2 |
| 23 | +Explanation: |
| 24 | +Level 1 sum = 1. |
| 25 | +Level 2 sum = 7 + 0 = 7. |
| 26 | +Level 3 sum = 7 + -8 = -1. |
| 27 | +So we return the level with the maximum sum which is level 2. |
| 28 | +``` |
| 29 | + |
| 30 | +**Example 2:** |
| 31 | +``` |
| 32 | +Input: root = [989,null,10250,98693,-89388,null,null,null,-32127] |
| 33 | +Output: 2 |
| 34 | +``` |
| 35 | + |
| 36 | +### Constraints |
| 37 | +- `The number of nodes in the tree is in the range [1, 10^4]` |
| 38 | +- `-10^5 <= Node.val <= 10^5` |
| 39 | + |
| 40 | +## Solution for Maximum Level Sum of a Binary |
| 41 | + |
| 42 | +### Approach |
| 43 | +The problem is to find the level in a binary tree that has the maximum sum of node values. To solve this, we use a breadth-first search (BFS) approach, which is well-suited for level-order traversal of a tree. BFS allows us to process nodes level by level, making it easy to calculate the sum of values at each level. |
| 44 | + |
| 45 | +#### Initial Checks and Setup: |
| 46 | + |
| 47 | +- If the root is null, return -1 as there are no levels in the tree. |
| 48 | +- Initialize a queue and add the root node to it. This queue will help us traverse the tree level by level. |
| 49 | +- Initialize variables to keep track of the maximum sum (maxSum), the level with the maximum sum (ans), and the current level (level). Set maxSum to a very small value to ensure any level sum will be larger initially. |
| 50 | +#### Level-Order Traversal Using BFS: |
| 51 | + |
| 52 | +- Use a while loop to process nodes until the queue is empty. |
| 53 | +- Increment the level variable at the start of each iteration of the while loop to represent the current level. |
| 54 | +- Determine the number of nodes at the current level (size), which is the current length of the queue. |
| 55 | +- Initialize a temporary sum variable (tempSum) to zero for storing the sum of values at the current level. |
| 56 | +#### Processing Each Level: |
| 57 | + |
| 58 | +- Use a for loop to iterate over all nodes at the current level. The loop runs size times. |
| 59 | +- For each node, dequeue it from the queue, add its value to tempSum, and enqueue its left and right children (if they exist). |
| 60 | +#### Update Maximum Sum and Level: |
| 61 | + |
| 62 | +- After processing all nodes at the current level, compare tempSum with maxSum. |
| 63 | +- If tempSum is greater than maxSum, update maxSum to tempSum and set ans to the current level. |
| 64 | +#### Return the Result: |
| 65 | + |
| 66 | +- Once all levels have been processed and the queue is empty, return ans, which holds the level number with the maximum sum. |
| 67 | +<Tabs> |
| 68 | + <TabItem value="Solution" label="Solution"> |
| 69 | + |
| 70 | +#### Implementation |
| 71 | + |
| 72 | +```jsx live |
| 73 | +function Solution() { |
| 74 | +class TreeNode { |
| 75 | + constructor(val = 0, left = null, right = null) { |
| 76 | + this.val = val; |
| 77 | + this.left = left; |
| 78 | + this.right = right; |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +var maxLevelSum = function(root) { |
| 83 | + if (!root) return -1; |
| 84 | + |
| 85 | + let ans = -1; |
| 86 | + let level = 0; |
| 87 | + let maxSum = Number.MIN_SAFE_INTEGER; |
| 88 | + const queue = [root]; |
| 89 | + |
| 90 | + while (queue.length > 0) { |
| 91 | + level++; |
| 92 | + const size = queue.length; |
| 93 | + let tempSum = 0; |
| 94 | + for (let i = 0; i < size; i++) { |
| 95 | + const curr = queue.shift(); |
| 96 | + tempSum += curr.val; |
| 97 | + if (curr.left) queue.push(curr.left); |
| 98 | + if (curr.right) queue.push(curr.right); |
| 99 | + } |
| 100 | + if (tempSum > maxSum) { |
| 101 | + ans = level; |
| 102 | + maxSum = tempSum; |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + return ans; |
| 107 | +}; |
| 108 | +function constructTreeFromArray(array) { |
| 109 | + if (!array.length) return null; |
| 110 | + |
| 111 | + let root = new TreeNode(array[0]); |
| 112 | + let queue = [root]; |
| 113 | + let i = 1; |
| 114 | + |
| 115 | + while (i < array.length) { |
| 116 | + let currentNode = queue.shift(); |
| 117 | + |
| 118 | + if (array[i] !== null) { |
| 119 | + currentNode.left = new TreeNode(array[i]); |
| 120 | + queue.push(currentNode.left); |
| 121 | + } |
| 122 | + i++; |
| 123 | + |
| 124 | + if (i < array.length && array[i] !== null) { |
| 125 | + currentNode.right = new TreeNode(array[i]); |
| 126 | + queue.push(currentNode.right); |
| 127 | + } |
| 128 | + i++; |
| 129 | + } |
| 130 | + return root; |
| 131 | +} |
| 132 | +const array = [1,7,0,7,-8,null,null] |
| 133 | +const root = constructTreeFromArray(array) |
| 134 | +const input = root |
| 135 | +const output = maxLevelSum(root) |
| 136 | + return ( |
| 137 | + <div> |
| 138 | + <p> |
| 139 | + <b>Input: </b>{JSON.stringify(array)} |
| 140 | + </p> |
| 141 | + <p> |
| 142 | + <b>Output:</b> {output.toString()} |
| 143 | + </p> |
| 144 | + </div> |
| 145 | + ); |
| 146 | +} |
| 147 | +``` |
| 148 | + |
| 149 | +### Code in Different Languages |
| 150 | + |
| 151 | +<Tabs> |
| 152 | + <TabItem value="JavaScript" label="JavaScript"> |
| 153 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 154 | + ```javascript |
| 155 | + var maxLevelSum = function(root) { |
| 156 | + if (!root) return -1; |
| 157 | + |
| 158 | + let ans = -1; |
| 159 | + let level = 0; |
| 160 | + let maxSum = Number.MIN_SAFE_INTEGER; |
| 161 | + const queue = [root]; |
| 162 | + |
| 163 | + while (queue.length > 0) { |
| 164 | + level++; |
| 165 | + const size = queue.length; |
| 166 | + let tempSum = 0; |
| 167 | + for (let i = 0; i < size; i++) { |
| 168 | + const curr = queue.shift(); |
| 169 | + tempSum += curr.val; |
| 170 | + if (curr.left) queue.push(curr.left); |
| 171 | + if (curr.right) queue.push(curr.right); |
| 172 | + } |
| 173 | + if (tempSum > maxSum) { |
| 174 | + ans = level; |
| 175 | + maxSum = tempSum; |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + return ans; |
| 180 | +}; |
| 181 | +``` |
| 182 | + </TabItem> |
| 183 | + <TabItem value="TypeScript" label="TypeScript"> |
| 184 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 185 | + ```typescript |
| 186 | + class TreeNode { |
| 187 | + val: number; |
| 188 | + left: TreeNode | null; |
| 189 | + right: TreeNode | null; |
| 190 | + constructor(val: number = 0, left: TreeNode | null = null, right: TreeNode | null = null) { |
| 191 | + this.val = val; |
| 192 | + this.left = left; |
| 193 | + this.right = right; |
| 194 | + } |
| 195 | +} |
| 196 | + |
| 197 | +function maxLevelSum(root: TreeNode | null): number { |
| 198 | + if (!root) return -1; |
| 199 | + |
| 200 | + let ans = -1; |
| 201 | + let level = 0; |
| 202 | + let maxSum = Number.MIN_SAFE_INTEGER; |
| 203 | + const queue: TreeNode[] = [root]; |
| 204 | + |
| 205 | + while (queue.length > 0) { |
| 206 | + level++; |
| 207 | + const size = queue.length; |
| 208 | + let tempSum = 0; |
| 209 | + for (let i = 0; i < size; i++) { |
| 210 | + const curr = queue.shift()!; |
| 211 | + tempSum += curr.val; |
| 212 | + if (curr.left) queue.push(curr.left); |
| 213 | + if (curr.right) queue.push(curr.right); |
| 214 | + } |
| 215 | + if (tempSum > maxSum) { |
| 216 | + ans = level; |
| 217 | + maxSum = tempSum; |
| 218 | + } |
| 219 | + } |
| 220 | + |
| 221 | + return ans; |
| 222 | +} |
| 223 | + |
| 224 | + ``` |
| 225 | + </TabItem> |
| 226 | + <TabItem value="Python" label="Python"> |
| 227 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 228 | + ```python |
| 229 | + # Definition for a binary tree node. |
| 230 | +class TreeNode: |
| 231 | + def __init__(self, val=0, left=None, right=None): |
| 232 | + self.val = val |
| 233 | + self.left = left |
| 234 | + self.right = right |
| 235 | + |
| 236 | +class Solution: |
| 237 | + def maxLevelSum(self, root: TreeNode) -> int: |
| 238 | + if not root: |
| 239 | + return -1 |
| 240 | + |
| 241 | + from collections import deque |
| 242 | + |
| 243 | + ans = -1 |
| 244 | + level = 0 |
| 245 | + max_sum = float('-inf') |
| 246 | + queue = deque([root]) |
| 247 | + |
| 248 | + while queue: |
| 249 | + level += 1 |
| 250 | + size = len(queue) |
| 251 | + temp_sum = 0 |
| 252 | + for _ in range(size): |
| 253 | + curr = queue.popleft() |
| 254 | + temp_sum += curr.val |
| 255 | + if curr.left: |
| 256 | + queue.append(curr.left) |
| 257 | + if curr.right: |
| 258 | + queue.append(curr.right) |
| 259 | + if temp_sum > max_sum: |
| 260 | + ans = level |
| 261 | + max_sum = temp_sum |
| 262 | + |
| 263 | + return ans |
| 264 | + |
| 265 | + ``` |
| 266 | + |
| 267 | + </TabItem> |
| 268 | + <TabItem value="Java" label="Java"> |
| 269 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 270 | +```java |
| 271 | +/** |
| 272 | + * Definition for a binary tree node. |
| 273 | + * public class TreeNode { |
| 274 | + * int val; |
| 275 | + * TreeNode left; |
| 276 | + * TreeNode right; |
| 277 | + * TreeNode() {} |
| 278 | + * TreeNode(int val) { this.val = val; } |
| 279 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 280 | + * this.val = val; |
| 281 | + * this.left = left; |
| 282 | + * this.right = right; |
| 283 | + * } |
| 284 | + * } |
| 285 | + */ |
| 286 | +import java.util.*; |
| 287 | + |
| 288 | +class Solution { |
| 289 | + public int maxLevelSum(TreeNode root) { |
| 290 | + if (root == null) return -1; |
| 291 | + |
| 292 | + int ans = -1; |
| 293 | + int level = 0; |
| 294 | + int maxSum = Integer.MIN_VALUE; |
| 295 | + Queue<TreeNode> queue = new LinkedList<>(); |
| 296 | + queue.add(root); |
| 297 | + |
| 298 | + while (!queue.isEmpty()) { |
| 299 | + level++; |
| 300 | + int size = queue.size(); |
| 301 | + int tempSum = 0; |
| 302 | + for (int i = 0; i < size; i++) { |
| 303 | + TreeNode curr = queue.poll(); |
| 304 | + tempSum += curr.val; |
| 305 | + if (curr.left != null) queue.add(curr.left); |
| 306 | + if (curr.right != null) queue.add(curr.right); |
| 307 | + } |
| 308 | + if (tempSum > maxSum) { |
| 309 | + ans = level; |
| 310 | + maxSum = tempSum; |
| 311 | + } |
| 312 | + } |
| 313 | + |
| 314 | + return ans; |
| 315 | + } |
| 316 | +} |
| 317 | + |
| 318 | +``` |
| 319 | +</TabItem> |
| 320 | + <TabItem value="C++" label="C++"> |
| 321 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 322 | +```cpp |
| 323 | +/** |
| 324 | + * Definition for a binary tree node. |
| 325 | + * struct TreeNode { |
| 326 | + * int val; |
| 327 | + * TreeNode *left; |
| 328 | + * TreeNode *right; |
| 329 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 330 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 331 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 332 | + * }; |
| 333 | + */ |
| 334 | +class Solution { |
| 335 | +public: |
| 336 | + int maxLevelSum(TreeNode* root) { |
| 337 | + int ans=-1; |
| 338 | + int level=0; |
| 339 | + int sum=INT_MIN; |
| 340 | + queue<TreeNode *> q; |
| 341 | + if(!root) return ans; |
| 342 | + |
| 343 | + q.push(root); |
| 344 | + |
| 345 | + while(!q.empty()){ |
| 346 | + |
| 347 | + level++; |
| 348 | + int size = q.size(); |
| 349 | + int temp=0; |
| 350 | + while(size--){ |
| 351 | + TreeNode *curr = q.front(); |
| 352 | + q.pop(); |
| 353 | + temp+=curr->val; |
| 354 | + |
| 355 | + if(curr->left) q.push(curr->left); |
| 356 | + if(curr->right) q.push(curr->right); |
| 357 | + |
| 358 | + } |
| 359 | + if(temp>sum) |
| 360 | + { |
| 361 | + ans=level; |
| 362 | + sum=temp; |
| 363 | + } |
| 364 | + } |
| 365 | + |
| 366 | + return ans; |
| 367 | + } |
| 368 | +}; |
| 369 | +``` |
| 370 | + </TabItem> |
| 371 | + </Tabs> |
| 372 | + |
| 373 | +#### Complexity Analysis |
| 374 | + ##### Time Complexity: $O(N)$ , because of tree traversal |
| 375 | + |
| 376 | + ##### Space Complexity: $O(1)$ |
| 377 | +</TabItem> |
| 378 | +</Tabs> |
| 379 | + |
| 380 | +## References |
| 381 | + |
| 382 | +- **LeetCode Problem**: [Maximum Level Sum of a Binary Tree](https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/description/) |
| 383 | + |
| 384 | +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/description/) |
| 385 | + |
0 commit comments