487. Floor Maximums

A hotel is modelled as a binary tree: the root is the top floor, and the children of the nodes on one floor make up the floor right below it. Every node stores the noise level that was measured in one room. Given the root of the tree as root, the manager wants to know the loudest reading on every floor.

Return an array whose first element is the largest value on the first floor (the one that contains the root), whose second element is the largest value on the second floor, and so on down to the deepest floor. Within a floor only existing nodes are compared. An empty tree gives an empty array.

Example 1

Input:
root = [4,9,2,3,5,null,7]
Output:
[4,9,7]
Explanation:

The floors hold {4}, {9, 2} and {3, 5, 7}, with maxima 4, 9 and 7.

Example 2

Input:
root = [-6,-9,-2,-7]
Output:
[-6,-2,-7]
Explanation:

The floors hold {-6}, {-9, -2} and {-7}, with maxima -6, -2 and -7.

Example 3

Input:
root = []
Output:
[]
Explanation:

An empty tree has no floors.

Constraints

0 ≤ number of nodes ≤ 105

-104 ≤ Node.val ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…