Find Largest Value in Each Tree Row

Srikanth
2 min readOct 24, 2023

--

Return the largest element in each row or level of the tree.

Intuition

In these type of problems, we use BFS because it traverses the tree level wise.

At each level, find the maximum element and add it to the result array.

Algorithm

  1. If the root is null, return the empty result array.
  2. Add root element to the queue.
  3. While the queue is not empty, do the following operations
  • store the current size of the queue. Because the queue contains the elements of current level
  • While iterating through the elements of the current level, track the max value and add left, right nodes to the queue.
  • After the iteration, add the max element to the result array

4. return the result array.

Code

class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
int size = queue.size();
int max = queue.peek().val;
for(int i = 0; i < size; i++) {
TreeNode current = queue.remove();
if(current.val > max) max = current.val;
if(current.left != null) queue.add(current.left);
if(current.right != null) queue.add(current.right);
}
res.add(max);
}
return res;
}
}

--

--

Srikanth
Srikanth

Written by Srikanth

Passionate writer in Programming, Backend Development

No responses yet