All problems

Problem 415

Diagonal Traversal of Binary Tree

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

Problem

Assign every node of a binary tree to a diagonal. The root is on diagonal 0, a right child stays on its parent's diagonal, and a left child is on the next diagonal (parent's diagonal + 1). Print the diagonals in order 0, 1, 2, ..., one per line. Within a diagonal, list the nodes in the order a preorder traversal (node, then left subtree, then right subtree) visits them.

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.

Output

Print one line per diagonal with its values separated by spaces.

Constraints

1 <= number of nodes <= 10000; -1000 <= value <= 1000

Example input

12
8 3 10 1 6 null 14 null null 4 7 13

Example output

8 10 14
3 6 7 13
1 4

Explanation

In the tree 8 / 3 10 / 1 6 _ 14 / _ _ 4 7 13, diagonal 0 is 8 10 14 (always going right), diagonal 1 is 3 6 7 13, and diagonal 2 is 1 4.

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

Previous: Boundary Traversal of Binary Tree Next: Construct Tree from Inorder and Postorder