Problem
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Examples
Example 1:
graph TD;
A[1]
B[3]
C[2]
D[5]
E[3]
F[9]
A --> B & C
B --> D & E
C ~~~ N1:::hidden
C --> F
classDef hidden display: none;
classDef highest fill:#ADD8E6,stroke:#0000FF,stroke-width:2px; class A,B,F highest;
| |
Example 2:
| |
Solution
Method 1 - Level order traversal
We need to find the largest value in each row of a binary tree. This problem can be efficiently solved using Breadth-First Search (BFS) traversal. In BFS, we traverse the tree level-by-level which is perfect for this problem as we need to consider each row separately.
Here are the steps:
- Initialize an empty list
ansto store the largest values. - Use a queue (FIFO) to help with the BFS traversal.
- Start by adding the root node to the queue.
- While the queue is not empty:
- Determine the number of nodes at the current level (using the queue size).
- Iterate over all nodes at this level, keeping track of the largest value.
- Add the children of the current node to the queue for the next level.
- After finishing the current level, append the largest value to
ans.
- Return the list
ans.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n)as we visit each node exactly once, wherenis the number of nodes in the tree. - 🧺 Space complexity:
O(n), as the maximum number of nodes that can be held in the queue at any given time is the width of the tree, which ismin the worst case.