Build Tree (In + Post)

Build Tree (In + Post)

Reconstruct a binary tree from its in-order and post-order traversals (all values distinct) and return the root.

buildTreeInPost(inorder, postorder)

Input format: inorder | postorder (space-separated values). Output the tree in level-order form (x for missing children).

Examples

inorder=9 3 15 20 7, postorder=9 15 7 20 3   // → 3 9 20 x x 15 7
inorder=1, postorder=1                        // → 1

Walkthrough

Thinking it through

Reconstructing a tree from two traversals works because each encodes complementary information. In-order tells you which values fall left versus right of a subtree's root, but never which value is the root. Post-order tells you exactly which value is the root — its last element — but not where the left/right split falls. Together, each supplies what the other is missing.

Why the last element of post-order is always the root

Post-order visits left-subtree, right-subtree, node. So a subtree's own root is always the last thing recorded — everything before it belongs to its children. For the whole tree, the last value in the full post-order sequence is the overall root.

Using in-order to find the split

Find the root's value in the in-order sequence. Since in-order visits left, node, right, everything before that position belongs to the left subtree, everything after to the right. "I know the root" becomes "I know exactly which values form each subtree."

Building the recursive approach

Work over a shrinking in-order window (lo/hi), with a pointer into post-order pointing at the next unconsumed value from the end. At each call: the current last unconsumed post-order value is this subtree's root; find its position in the in-order window for the split. Since post-order is left, then right, then node, the value just before the root belongs to the right subtree — so build the right subtree first, then the left, to consume post-order back-to-front correctly. lo exceeding hi means an empty subtree.

Why this is efficient

A value-to-index lookup over in-order turns finding the split into O(1) instead of a linear scan, so each of the n calls does constant extra work — O(n) time, O(n) space for the lookup table and the tree.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.