All problems

Problem 919

Reverse Odd Levels of Binary Tree

Medium · 20 pts · Tree, Breadth-First Search, Depth-First Search

Problem

The binary tree is perfect: every inner node has two children and all leaves are on the same level. Reverse the values on every odd level (levels are numbered from 0 at the root), so that on level 1, 3, 5, ... the values read from right to left. Only the values move; the shape stays the same. Print the tree in level order. A breadth-first search collects each odd level's nodes, then swaps values from both ends.

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode. The tree is perfect.

Output

Print the tree as level-order tokens separated by spaces, using null for missing children and without trailing nulls.

Constraints

1 <= number of nodes <= 2^14 - 1; 0 <= value <= 10^5

Example input

7
2 3 5 8 13 21 34

Example output

2 5 3 8 13 21 34

Explanation

In 2 3 5 8 13 21 34, level 1 holds 3 5, which becomes 5 3; level 2 is even and stays. The result is 2 5 3 8 13 21 34.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Step-By-Step Directions From a Binary Tree Node to Another Next: Most Frequent Subtree Sum