All problems

Problem 912

Add One Row to Tree

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

Problem

Insert a new row of nodes with value V at depth D (the root is at depth 1). For every node at depth D - 1, create two new nodes with value V: the new left node takes the old left subtree as its left child, and the new right node takes the old right subtree as its right child. If D is 1, create a new root with value V whose left child is the whole original tree. Print the new tree in level order.

Input

The first line contains V and D. The next two lines describe the tree: N, the number of tokens, then N level-order tokens with 'null' for missing children.

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 <= 1000; 1 <= D <= height of the tree + 1; -100 <= values <= 100

Example input

1 2
6
4 2 6 3 1 5

Example output

4 1 1 2 null null 6 3 1 5

Explanation

Adding a row of 1s at depth 2 under the root 4 of 4 2 6 3 1 5 puts new nodes 1 and 1 between 4 and its children: 4 1 1 2 null null 6 3 1 5.

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

Previous: Maximum Binary Tree Next: Delete Nodes And Return Forest