-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmax_sum_level.go
36 lines (33 loc) · 903 Bytes
/
max_sum_level.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package problem1161
import . "leetcodedaily/helpers/binarytree"
/*
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.
*/
func maxLevelSum(root *TreeNode) int {
var maxLevel, maxSum, curSum, curLevel int
var curNodes, nextNodes []*TreeNode
maxLevel, curLevel = 1, 1
maxSum = root.Val
curNodes = []*TreeNode{root}
for len(curNodes) > 0 {
curSum = 0
nextNodes = []*TreeNode{}
for i := range curNodes {
curSum += curNodes[i].Val
if curNodes[i].Left != nil {
nextNodes = append(nextNodes, curNodes[i].Left)
}
if curNodes[i].Right != nil {
nextNodes = append(nextNodes, curNodes[i].Right)
}
}
if curSum > maxSum {
maxSum = curSum
maxLevel = curLevel
}
curLevel++
curNodes = nextNodes
}
return maxLevel
}