1665. Odd Floors Reversed

A tournament bracket is drawn as a binary tree with the root on level 0. For a mirror-style display, the scores on every odd-numbered level must be shown in the opposite left-to-right order, while the shape of the tree stays exactly as it is. Only the values stored in the nodes of an odd level are rearranged among the nodes that already exist on that level.

The tree is not guaranteed to be perfect: a level may have gaps, and then only the nodes that actually exist take part, keeping their left-to-right order. Level 0 and all even levels are untouched. Change the tree in place; the method returns nothing and the judge prints the tree from root afterwards. Aim for O(n) time and O(w) extra space, where w is the widest level.

Example 1

Input:
root = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
Output:
[1,3,2,4,5,6,7,15,14,13,12,11,10,9,8]
Explanation:

Level 1 holds 2,3 and level 3 holds 8 through 15; both odd levels are mirrored while levels 0 and 2 stay as they are.

Example 2

Input:
root = [7,1,9,null,4,6,null,2,null,null,8]
Output:
[7,9,1,null,4,6,null,8,null,null,2]
Explanation:

The tree has gaps, so level 1 swaps 1 and 9, and level 3 swaps its only two nodes 2 and 8; the shape of the tree is unchanged.

Constraints

1 ≤ nodes ≤ 500; -1000 ≤ Node.val ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Graded
Your answer is read from root after your method returns.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(w)

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…