Skip to content

Commit d1327e1

Browse files
authored
Create 1161-maximum-level-sum-of-a-binary-tree.js
1 parent 5992503 commit d1327e1

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {number}
11+
*/
12+
const maxLevelSum = function(root) {
13+
if (root == null) return 0
14+
let res = 1
15+
let cur = [root]
16+
let next = []
17+
let max = Number.MIN_SAFE_INTEGER
18+
let sum = 0
19+
let level = 1
20+
while (cur.length) {
21+
let node = cur.pop()
22+
if (node.left) next.push(node.left)
23+
if (node.right) next.push(node.right)
24+
sum += node.val
25+
if (cur.length === 0) {
26+
cur = next
27+
next = []
28+
if (sum > max) {
29+
res = level
30+
max = sum
31+
}
32+
sum = 0
33+
level++
34+
}
35+
}
36+
37+
return res
38+
}

0 commit comments

Comments
 (0)