Recover the Preorder of a BST from Its Postorder Listing
Trees & GraphsAuto-graded · 26 test casesLast updated
Turn the postorder listing of a distinct-valued BST into its preorder listing in linear time, including chain-shaped trees, using a monotonic stack over the reversed input.
A binary search tree (BST) stores distinct integers. Each node has at most one left child and at most one right child, and for every node x:
- every value in the left subtree of
xis strictly smaller thanx; - every value in the right subtree of
xis strictly larger thanx.
An empty subtree contributes nothing to a traversal.
Traversal orders
For a (sub)tree rooted at node x, the two listings are defined recursively:
- Postorder: the postorder of the left subtree, then the postorder of the right subtree, then
x. - Preorder:
x, then the preorder of the left subtree, then the preorder of the right subtree.
In both orders the left subtree always comes before the right subtree. In postorder the last element of the whole listing is the root of the tree.
Task
You are given postorder, the postorder listing of some BST with distinct values. Because the values are distinct and the tree obeys the BST rule, exactly one tree produces this listing. Rebuild that tree (conceptually) and return its preorder listing as a list of integers.
Write bst_preorder_from_postorder(postorder), which takes the postorder list and returns the preorder list. The returned list has the same length as the input and contains the same values, each exactly once, in preorder. The order of the returned elements matters, and the input list should be treated as read-only.
Rules
- The input is always a valid postorder listing of some BST with distinct values. You do not need to validate it.
- A one-element input is a tree with a single node, so the output is that same one-element list.
- Trees can be completely lopsided. For example, every node may have only a right child, or only a left child, so the height can equal the number of values. Your solution must handle this without exceeding Python's recursion limit.
- The solution must run in $O(n)$ time, where $n = $
len(postorder).
Constraints
1 <= len(postorder) <= 10^4-10^9 <= postorder[i] <= 10^9- All values in
postorderare distinct. postorderis a valid BST postorder listing.- Required time complexity: $O(n)$.
Examples
Example 1
Input: bst_preorder_from_postorder([1, 3, 2, 5, 7, 6, 4])
Output: [4, 2, 1, 3, 6, 5, 7]
Example 2
Input: bst_preorder_from_postorder([2, 4, 3, 8, 7, 5])
Output: [5, 3, 2, 4, 7, 8]
Example 3
Input: bst_preorder_from_postorder([3, 2, 1])
Output: [1, 2, 3]
Hints
Hint 1
Postorder is left, right, node. Read it from right to left and you get node, right subtree, left subtree, which is a preorder that visits the right side first.
Hint 2
While scanning in reverse, keep a stack of nodes that may still receive a left child, strictly increasing from bottom to top. Compare each new value with the top of the stack to decide where it attaches.
Hint 3
If the new value is larger than the top, it is the top's right child. Otherwise pop everything larger than it; the last node popped is its parent and the value becomes that node's left child. Produce the final preorder with an iterative traversal.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Postorder lists a node's left subtree, right subtree, then the node. Reading it backwards gives the node, then its right subtree, then its left subtree. That is a preorder that visits right before left, so every node appears before all of its descendants.
Scan the reversed sequence while maintaining a stack of nodes that may still receive a left child. The stack is strictly increasing from bottom to top, and its top is always the value processed just before the current one. For each new value v:
vis larger than the top of the stack. In the reversed order, a node's right subtree starts immediately after the node. Sovis the right child of the top.vis smaller than the top. Pop every node greater thanv. The last node popped is the smallest stack value that exceedsv, and it is the nearest ancestor whose left slot is still open. Makevits left child.
Then push v. After the scan, the tree is stored in two maps (left, right), and an iterative preorder traversal (node, left, right) produces the answer.
Why it is correct
- Invariant: before pushing
v, everything larger thanvis removed, so the stack stays strictly increasing. - Right-child case: if nothing is popped, then
vexceeds the previously processed node. In node-right-left order, the only value that can directly follow a node and be larger than it is the root of that node's right subtree. That node was just pushed and has no right child yet, so nothing is overwritten. - Left-child case:
vcannot be in the previous node's right subtree, so it belongs to the left subtree of an earlier node. BST ordering forces the parent to be the smallest already-seen value greater thanv, which is the last one popped. Nodes popped earlier are larger but lie inside that parent's right subtree. Nodes left on the stack are smaller thanv, and their right sides are already settled. - Each slot is filled once: a node leaves the stack at the moment it receives its left child, and only the node pushed right before
vcan receive a right child.
Both phases are iterative, so a chain-shaped tree of height 10^4 causes no recursion problems.
Complexity
- Time: O(n). Each value is pushed once and popped at most once, so the inner loop does O(n) work in total. The preorder pass visits each node once.
- Space: O(n) for the stack, the two maps, and the output.
Reference solution
from typing import List
def bst_preorder_from_postorder(postorder: List[int]) -> List[int]:
n = len(postorder)
left = {}
right = {}
root = postorder[-1]
stack = [root] # strictly increasing from bottom to top
# Reversed postorder visits: node, right subtree, left subtree.
for i in range(n - 2, -1, -1):
v = postorder[i]
parent = None
# Pop every node larger than v; the last one popped is v's parent.
while stack and v < stack[-1]:
parent = stack.pop()
if parent is not None:
left[parent] = v
else:
# v is larger than the previous node: it is that node's right child.
right[stack[-1]] = v
stack.append(v)
# Iterative preorder: node, left, right.
out = []
st = [root]
while st:
x = st.pop()
out.append(x)
if x in right:
st.append(right[x])
if x in left:
st.append(left[x])
return out