All problems

Problem 417

BST from Preorder Traversal

Medium · 20 pts · Tree, Binary Search Tree, Stack

Problem

You are given the preorder traversal (node, left subtree, right subtree) of a binary search tree with distinct values. In a binary search tree, every value in a node's left subtree is smaller than the node and every value in its right subtree is larger. Rebuild the tree and print its postorder traversal (left subtree, right subtree, node). Inserting the values one by one works in O(N²); passing value bounds down the recursion builds it in O(N).

Input

First line: N. Second line: the preorder traversal.

Output

Print the postorder traversal, separated by spaces.

Constraints

1 <= N <= 1000; -10^4 <= value <= 10^4; values are distinct

Example input

6
8 5 1 7 10 12

Example output

1 7 5 12 10 8

Explanation

From the preorder 8 5 1 7 10 12, the root is 8, its left subtree holds 5 1 7 and its right subtree holds 10 12. The postorder is 1 7 5 12 10 8.

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

Previous: Construct Tree from Inorder and Postorder Next: Two Sum in a BST