# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
ans, maxSum = 1, root.val
level, q = 1, [root]
while q:
sum, nq = 0, []
for node in q:
sum += node.val
if node.left:
nq.append(node.left)
if node.right:
nq.append(node.right)
if sum > maxSum:
ans, maxSum = level, sum
q = nq
level += 1
return ans
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxLevelSum(root *TreeNode) int {
ans, maxSum := 1, root.Val
q := []*TreeNode{root}
for level := 1; len(q) > 0; level++ {
tmp := q
q = nil
sum := 0
for _, node := range tmp {
sum += node.Val
if node.Left != nil {
q = append(q, node.Left)
}
if node.Right != nil {
q = append(q, node.Right)
}
}
if sum > maxSum {
ans, maxSum = level, sum
}
}
return ans
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxLevelSum(root *TreeNode) (ans int) {
sum := []int{}
var dfs func(*TreeNode, int)
dfs = func(node *TreeNode, level int) {
if level == len(sum) {
sum = append(sum, node.Val)
} else {
sum[level] += node.Val
}
if node.Left != nil {
dfs(node.Left, level+1)
}
if node.Right != nil {
dfs(node.Right, level+1)
}
}
dfs(root, 0)
for i, s := range sum {
if s > sum[ans] {
ans = i
}
}
return ans + 1 // 层号从 1 开始
}