All problems

Problem 263

Sorted Array to Balanced BST

Easy · 10 pts · Tree, Binary Search Tree, Divide and Conquer

Problem

You are given a sorted array of distinct integers. Build a height-balanced binary search tree from it with this exact rule: the root is the middle element of the range, at index (lo + hi) / 2 rounded down, so for an even-length range it is the left of the two middle elements. The elements before it form the left subtree and the elements after it form the right subtree, built the same way. Print the preorder traversal of the tree (node, left subtree, right subtree). The rule fixes the tree completely, so a direct recursive implementation produces the expected output.

Input

First line: integer N. Second line: N sorted distinct integers.

Output

Print the preorder traversal, space-separated.

Constraints

1 <= N <= 10000; -10000 <= value <= 10000

Example input

5
-10 -3 0 5 9

Example output

0 -10 -3 5 9

Explanation

For -10 -3 0 5 9, the middle element 0 is the root. The left part -10 -3 has middle index 0, so -10 is its root and -3 its right child. The right part 5 9 gives 5 with right child 9. Preorder is 0 -10 -3 5 9.

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

Previous: Maximum Width of Binary Tree Next: Path Sum II