LeetCode Solutions

515. Find Largest Value in Each Tree Row

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  vector<int> largestValues(TreeNode* root) {
    if (root == nullptr)
      return {};

    vector<int> ans;
    queue<TreeNode*> q{{root}};

    while (!q.empty()) {
      int maxi = INT_MIN;
      for (int sz = q.size(); sz > 0; --sz) {
        TreeNode* node = q.front();
        q.pop();
        maxi = max(maxi, node->val);
        if (node->left)
          q.push(node->left);
        if (node->right)
          q.push(node->right);
      }
      ans.push_back(maxi);
    }

    return ans;
  }
};
			

class Solution {
  public List<Integer> largestValues(TreeNode root) {
    if (root == null)
      return new ArrayList<>();

    List<Integer> ans = new ArrayList<>();
    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));

    while (!q.isEmpty()) {
      int max = Integer.MIN_VALUE;
      for (int sz = q.size(); sz > 0; --sz) {
        TreeNode node = q.poll();
        max = Math.max(max, node.val);
        if (node.left != null)
          q.offer(node.left);
        if (node.right != null)
          q.offer(node.right);
      }
      ans.add(max);
    }

    return ans;
  }
}
			

class Solution:
  def largestValues(self, root: Optional[TreeNode]) -> List[int]:
    if not root:
      return []

    ans = []
    q = deque([root])

    while q:
      maxi = -math.inf
      for _ in range(len(q)):
        root = q.popleft()
        maxi = max(maxi, root.val)
        if root.left:
          q.append(root.left)
        if root.right:
          q.append(root.right)
      ans.append(maxi)

    return ans