Maximum Level Sum of a Binary Tree

MediumTreeDepth-First SearchBreadth-First SearchBinary Tree

Solution

import { TreeNode } from '@algorithm/lib';
 
export function maxLevelSum(root: TreeNode | null): number {
  if (root === null) {
    return 0;
  }
  let [maxValue, minLevel] = [root.val, 1];
 
  let currentLevel = 1;
  let currentNodes: TreeNode[] = [root];
  while (0 < currentNodes.length) {
    let totalValue = 0;
    const nextNodes: TreeNode[] = [];
    for (const currentNode of currentNodes) {
      totalValue += currentNode.val;
      currentNode.left && nextNodes.push(currentNode.left);
      currentNode.right && nextNodes.push(currentNode.right);
    }
    if (maxValue < totalValue) {
      [maxValue, minLevel] = [totalValue, currentLevel];
    }
 
    currentLevel += 1;
    currentNodes = nextNodes;
  }
 
  return minLevel;
}