Reconstruct BST from preorder

Write codeMedium30 min

Your task

You are given the preorder traversal of a binary search tree (all values distinct). Reconstruct the BST and return its postorder traversal, without explicitly building node objects if you prefer. Use the BST property: in the preorder sequence the first value is the root, the next run of smaller values is the left subtree, and the remaining values (each less than an upper bound) form the right subtree, so a single linear scan with a moving index and an upper-bound argument reconstructs it in O(n). Return the postorder list.

Examples

bst_preorder_to_postorder(preorder: list[int]) -> list[int]
Example 1
Inputbst_preorder_to_postorder([8, 5, 1, 7, 10, 12])
Output[1, 7, 5, 12, 10, 8]