LeetcodeJun 02, 2025

Find Largest Value in Each Tree Row

Hazrat Ali

Leetcode

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]


Solution
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
const largestValues = root => {
  if (!root) {
    return [];
  }

  const result = [];
  const queue = [root, null];
  let max = Number.MIN_SAFE_INTEGER;

  while (queue.length) {
    const node = queue.shift();

    if (node) {
      max = Math.max(max, node.val);

      if (node.left) {
        queue.push(node.left);
      }

      if (node.right) {
        queue.push(node.right);
      }
    } else {
      result.push(max);
      max = Number.MIN_SAFE_INTEGER;

      if (queue.length) {
        queue.push(null);
      }
    }
  }

  return result;
};





Comments