All problems

Problem 146

Invert Binary Tree

Easy · 10 pts · Tree, Depth-First Search, Binary Tree

Problem

You are given a binary tree. Invert it, which means swapping the left and right child of every node, so that the tree becomes its mirror image. Print the inverted tree in level order, using 'null' for missing children and leaving out trailing nulls at the end. Recursively: invert the left and right subtrees and then swap them. A breadth-first walk that swaps the children of every node it visits works just as well.

Input

First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).

Output

Print the inverted tree in level order, using 'null' for missing children and without trailing nulls, space-separated.

Constraints

1 <= number of nodes <= 100; -100 <= value <= 100

Example input

7
4 2 7 1 3 6 9

Example output

4 7 2 9 6 3 1

Explanation

The tree 4 with children 2 and 7, and grandchildren 1 3 under 2 and 6 9 under 7, becomes 4 with children 7 and 2, and grandchildren 9 6 under 7 and 3 1 under 2. In level order that is 4 7 2 9 6 3 1.

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

Previous: Binary Tree Level Order Traversal Next: Same Tree