515. Find Largest Value in Each Tree Row
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the largest value present in each row of a binary tree. The rows are 0-indexed. This problem structure naturally suggests a level-by-level traversal of the tree, for which Breadth-First Search (BFS) is an ideal algorithm.
Solution
Find Largest Value in Each Tree Row in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
# Handle the edge case of an empty tree.
if not root:
return []
result = []
queue = deque([root])
# Process the tree level by level.
while queue:
level_size = len(queue)
# Initialize max_val to negative infinity
# to correctly handle negative node values.
max_val = float('-inf')
# Iterate through all nodes in the current level.
for _ in range(level_size):
node = queue.popleft()
# Update the maximum value for the current level.
max_val = max(max_val, node.val)
# Add children to the queue for the next level.
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# After iterating through the level, add the found maximum to the result.
result.append(max_val)
return result
Find Largest Value in Each Tree Row in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
// Handle the edge case of an empty tree.
if (root == null) {
return new ArrayList<>();
}
List<Integer> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
// Process the tree level by level.
while (!queue.isEmpty()) {
int levelSize = queue.size();
// Initialize maxVal to the smallest possible integer value
// to correctly handle negative node values.
int maxVal = Integer.MIN_VALUE;
// Iterate through all nodes in the current level.
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
// Update the maximum value for the current level.
maxVal = Math.max(maxVal, node.val);
// Add children to the queue for the next level.
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
// After iterating through the level, add the found maximum to the result.
result.add(maxVal);
}
return result;
}
}
Find Largest Value in Each Tree Row in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
// Handle the edge case of an empty tree.
if (!root) {
return {};
}
vector<int> result;
queue<TreeNode*> q;
q.push(root);
// Process the tree level by level.
while (!q.empty()) {
int level_size = q.size();
// Initialize max_val to the smallest possible integer value
// to correctly handle negative node values.
int max_val = numeric_limits<int>::min();
// Iterate through all nodes in the current level.
for (int i = 0; i < level_size; ++i) {
TreeNode* node = q.front();
q.pop();
// Update the maximum value for the current level.
max_val = max(max_val, node->val);
// Add children to the queue for the next level.
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
// After iterating through the level, add the found maximum to the result.
result.push_back(max_val);
}
return result;
}
};
Find Largest Value in Each Tree Row in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function largestValues(root: TreeNode | null): number[] {
// Handle the edge case of an empty tree.
if (!root) {
return [];
}
const result: number[] = [];
// Use an array as a queue. `push` to enqueue, `shift` to dequeue.
const queue: TreeNode[] = [root];
// Process the tree level by level.
while (queue.length > 0) {
const levelSize = queue.length;
// Initialize maxVal to negative infinity
// to correctly handle negative node values.
let maxVal = -Infinity;
// Iterate through all nodes in the current level.
for (let i = 0; i < levelSize; i++) {
// The non-null assertion `!` is safe because we know the queue is not empty here.
const node = queue.shift()!;
// Update the maximum value for the current level.
maxVal = Math.max(maxVal, node.val);
// Add children to the queue for the next level.
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
// After iterating through the level, add the found maximum to the result.
result.push(maxVal);
}
return result;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.