Leetcode 515. Find Largest Value in Each Tree Row
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
For this solution, we’ll implement the BFS approach.
import java.util.*;
public class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
int maxVal = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
TreeNode currentNode = queue.poll();
maxVal = Math.max(maxVal, currentNode.val);
if (currentNode.left != null) queue.add(currentNode.left);
if (currentNode.right != null) queue.add(currentNode.right);
}
result.add(maxVal);
}
return result;
}
// 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;
}
}
}
This approach efficiently finds the largest value in each row using level-order traversal, ensuring a straightforward and understandable implementation.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?