Skip to main content

Find Largest Value in Each Tree Row

LeetCode 515 | Difficulty: Medium​

Medium

Problem 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.

When to use

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.

When to use

Level-order traversal, level-based aggregation, right/left side view.


Solutions​

Solution 1: C# (Best: 296 ms)​

MetricValue
Runtime296 ms
MemoryN/A
Date2018-07-13
Solution
/**
* 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​

ApproachTimeSpace
Tree Traversal$O(n)$$O(h)$

Interview Tips​

Key Points
  • 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.