Recursion

Layer with Max Sum

Tree BFS

Given the root of a binary tree root, determine which layer has the largest sum, and return its layer number.

Layers are indexed at 1. If there are multiple solutions for a given tree, you can return any one of the solutions.

Example:

=> returns 2\notag \Large \texttt{=> returns 2}

Explanation: Layer number 2 has the highest sum of five, so we return 2. Layer 1 has a sum of one, and Layer 3 has a sum of zero.

First Few Test Cases:

We should use a BFS, since we need to compute the sum over each layer. Here's the code for a BFS:

To solve this problem, we need to keep track of the maximum sum over any layer we've seen so far, maxSum. We also need to return the layer that has the maximum sum, bestLayer. This requires that we keep track of which layer we're on currLayer.

Here's how you modify the above BFS to do this:

Time Complexity O(n)O(n). We loop through all the nodes.

Space Complexity O(n)O(n). The queue might contain all the nodes, so it uses O(n)O(n) memory. We store 3 variables, which is O(3)=O(1)O(3) = O(1) memory. This is a total of O(1)+O(n)=O(n)O(1) + O(n) = O(n) memory.

Mark as Completed:
Submits:
layerMaxSum
Imports:
TreeNode
Test your code to get an output here!
layerMaxSum(
)
Test your code to get an output here!