Find Largest Value in Each Tree Row

medium tree bfs

Problem

Given the root of a binary tree, return the largest value in each row of the tree (zero-indexed).

Inputtree = [1, 3, 2, 5, 3, null, 9]
Output[1, 3, 9]
Row 0 max = 1, row 1 max = 3, row 2 max = 9.

from collections import deque

def largest_values(root):
    if not root:
        return []
    q = deque([root])
    ans = []
    while q:
        sz = len(q)
        best = float("-inf")
        for _ in range(sz):
            n = q.popleft()
            if n.val > best:
                best = n.val
            if n.left:
                q.append(n.left)
            if n.right:
                q.append(n.right)
        ans.append(best)
    return ans
function largestValues(root) {
  if (!root) return [];
  const ans = [];
  let level = [root];
  while (level.length) {
    let best = -Infinity;
    const next = [];
    for (const n of level) {
      if (n.val > best) best = n.val;
      if (n.left) next.push(n.left);
      if (n.right) next.push(n.right);
    }
    ans.push(best);
    level = next;
  }
  return ans;
}
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if (root == null) return ans;
        Deque<TreeNode> q = new ArrayDeque<>();
        q.offer(root);
        while (!q.isEmpty()) {
            int sz = q.size();
            int best = Integer.MIN_VALUE;
            for (int i = 0; i < sz; i++) {
                TreeNode n = q.poll();
                best = Math.max(best, n.val);
                if (n.left != null) q.offer(n.left);
                if (n.right != null) q.offer(n.right);
            }
            ans.add(best);
        }
        return ans;
    }
}
vector<int> largestValues(TreeNode* root) {
    vector<int> ans;
    if (!root) return ans;
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty()) {
        int sz = q.size(), best = INT_MIN;
        for (int i = 0; i < sz; i++) {
            TreeNode* n = q.front(); q.pop();
            best = max(best, n->val);
            if (n->left) q.push(n->left);
            if (n->right) q.push(n->right);
        }
        ans.push_back(best);
    }
    return ans;
}
Time: O(n) Space: O(w)