All problems

Problem 745

Insert into a Binary Search Tree

Medium · 20 pts · Tree, Binary Search Tree

Problem

Insert a new value X into a binary search tree with distinct values; X is not already in the tree. Use the standard insertion: starting at the root, go left when X is smaller than the current node and right when it is larger, and attach X as a new leaf where the path runs out. Print the resulting tree in level order. Do not rebalance or restructure the tree in any other way.

Input

The first line contains X. The next two lines describe the BST: N, the number of tokens, then N level-order tokens with 'null' for missing children (N may be 0 for an empty tree).

Output

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

Constraints

0 <= number of nodes <= 10000; values and X are distinct integers between -10^8 and 10^8

Example input

5
5
4 2 7 1 3

Example output

4 2 7 1 3 5

Explanation

Inserting 5 into the BST 4 2 7 1 3: 5 > 4 goes right to 7, then 5 < 7 goes left, where 7 has no child, so 5 becomes the left child of 7. The tree becomes 4 2 7 1 3 5.

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

Previous: Floor and Ceil in a BST Next: Inorder Successor in a BST