Find Largest Value in Each Tree Row
LeetCode 515 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Example 1:

Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]
Example 2:
Input: root = [1,2,3]
Output: [1,3]
Constraints:
- The number of nodes in the tree will be in the range `[0, 10^4]`.
- `-2^31 <= Node.val <= 2^31 - 1`
Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Approachβ
Tree DFSβ
Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β go right β combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.
Path problems, subtree properties, tree structure manipulation.
Tree BFS (Level-Order)β
Use a queue to process the tree level by level. At each level, process all nodes in the queue, then add their children. Track the level size to know when one level ends and the next begins.
Level-order traversal, level-based aggregation, right/left side view.
Solutionsβ
Solution 1: C# (Best: 296 ms)β
| Metric | Value |
|---|---|
| Runtime | 296 ms |
| Memory | N/A |
| Date | 2018-07-13 |
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<int> LargestValues(TreeNode root) {
Queue<TreeNode> level = new Queue<TreeNode>();
List<int> result = new List<int>();
if(root==null) return result;
level.Enqueue(root);
while(level.Count!=0)
{
int rowCount = level.Count;
var max = Int32.MinValue;
for (int i = 0; i < rowCount; i++)
{
var front = level.Dequeue();
if (front.left != null) level.Enqueue(front.left);
if(front.right!=null) level.Enqueue(front.right);
if(max<front.val) max = front.val;
}
result.Add(max);
}
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Tree Traversal | $O(n)$ | $O(h)$ |
Interview Tipsβ
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Consider: "What information do I need from each subtree?" β this defines your recursive return value.