Problem : https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/
This is an easy problem which can be solved by either DFS or BFS.
But it needs to be aware that because node may have negative value, we cannot determine the final sum of a level until traversal is completed.
Time Complexity = O (N + N)
# 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:
levels = []
stack = [(root, 0)]
while stack:
node, index = stack.pop()
if index == len(levels):
levels.append(node.val)
else:
levels[index] += node.val
if node.right:
stack.append((node.right, index + 1))
if node.left:
stack.append((node.left, index + 1))
mxSoFar = levels[0]
miLevel = 0
for level, sums in enumerate(levels):
if sums > mxSoFar:
mxSoFar = sums
miLevel = level
return miLevel + 1