Construct BT from Preorder and Inorder
Construct Binary Tree from Preorder and Inorder Traversal is LeetCode 105 (Medium). You get two arrays that describe the same binary tree:
preorderlists each node, then its left subtree, then its right subtree.inorderlists each node's left subtree, then the node, then its right subtree.
Rebuild the tree and return its root. All values are distinct, so each value names exactly one node. There are at most 3,000 nodes, and an O(n) build is the expected answer.
- 1 <= preorder.length <= 3000
- inorder.length == preorder.length
- -3000 <= preorder[i], inorder[i] <= 3000
- preorder and inorder consist of unique values.
- Each value of inorder also appears in preorder.
- preorder is guaranteed to be the preorder traversal of the tree.
- inorder is guaranteed to be the inorder traversal of the tree.
Intuition
In preorder, every subtree is written as one unbroken block: its root first, then the block of its left subtree, then the block of its right subtree. What preorder does not say is where the left block ends.
Inorder answers that. It writes the left subtree, then the root, then the right subtree, so the root's position in inorder tells you how many values sit in its left subtree. Both arrays then split into left and right parts of matching sizes, and each part is solved the same way.
One shared index reading preorder from the front hands out roots in the order the recursion needs: a root, its whole left subtree, then its whole right subtree.
Two listings of the same tree, one fixing the order of the roots and the other fixing the size of each side, point to divide and conquer on index ranges. A map from value to position turns each split into a single lookup.
Approach
Before reading on, take preorder [3, 9, 20, 15, 7] and inorder [9, 3, 15, 20, 7]. Decide which value is the root, how many values belong to its left subtree, and which preorder values those are. Then repeat the same reasoning for the right part.
Record where each value sits in inorder
Build a map from each value to its index in inorder, once. Every call needs its root's position, and the map answers that in O(1) instead of a scan.
Describe a subtree by its inorder range
build(lo, hi) builds the subtree whose values are inorder[lo..hi]. When lo > hi the range holds no values, so the call returns nothing and leaves the preorder index where it is.
Take the next preorder value as the root
Make a node from preorder[i] and move i forward by one. Preorder writes a subtree's root before anything else in it, so the next unread value is always the root of the range this call is building.
Build the left side, then the right side
Look up the root's position mid. Build node.left from lo..mid - 1, then node.right from mid + 1..hi. Preorder lists the whole left block before the right block, so the shared index meets the left subtree's values first.
Start with the whole array
With i = 0, call build(0, n - 1) and return the node it creates. That node holds preorder[0], the overall root.
Code in Python, C++ and Java
Common pitfalls
Building the right side before the left
node.right = build(mid + 1, hi) node.left = build(lo, mid - 1)
node.left = build(lo, mid - 1) node.right = build(mid + 1, hi)
The shared index then hands the left subtree's values to the right side. On preorder [3, 9, 20, 15, 7], the right side of 3 should be 20, 15 and 7, but the next value read is 9, so 9 becomes the root of a side it does not belong to and the tree comes out wrong.
Giving each call its own copy of the index
def build(i, lo, hi):
...
node.left = build(i + 1, lo, mid - 1)
node.right = build(i + 1, mid + 1, hi)nonlocal i # one index that every call moves forward
The right side cannot start at i + 1; it starts after however many values the left side used, and a copied index cannot know that number. On [3, 9, 20, 15, 7] both children of 3 read 9 as their root.
Slicing preorder one value short
node.left = self.buildTree(preorder[1:mid], inorder[:mid])
node.left = self.buildTree(preorder[1:mid + 1], inorder[:mid])
The left subtree has mid values, and they sit right after the root, at indexes 1 to mid. Cutting at mid drops one. On [3, 9, 20, 15, 7] and [9, 3, 15, 20, 7], mid is 1, so the left call gets an empty preorder, returns nothing, and 9 never appears in the tree.
Edge cases
When every node has only a left child, each call recurses once more, so the recursion is 3,000 calls deep. That is fine in C++ and Java; plain Python stops at depth 1,000, so raise the limit with sys.setrecursionlimit if your runner keeps the default.
Complexity
Construct BT from Preorder and Inorder FAQ
Which pairs of traversals determine a unique binary tree?
A pair that includes inorder: inorder with preorder (this problem), or inorder with postorder. Preorder with postorder is not enough in general: preorder [1, 2] and postorder [2, 1] fit both a tree where 2 is the left child and one where it is the right child.
Can the tree be rebuilt from preorder alone?
Not for a general binary tree, because preorder never says where a left subtree ends. It can for a binary search tree, since the values themselves split the sides: everything smaller than a node goes left.