Rebuilding a tree

Root, left and right Β· Part of Strategies

Key idea

Practice

6 questions Β· about 3 min

Explained step by step

Divide and conquer

Given the preorder and the inorder of a binary tree with distinct values, the whole tree can be rebuilt. It is a classic divide and conquer problem: the root is built and 2 subproblems remain, building the left subtree and the right one. They are independent, because they share no nodes. And they are combined by hanging them from the root. With 5 nodes, root 3 leaves 1 node on the left and 3 on the right.

Depth-first search (DFS)

Both traversals have 3 parts, but in a different order. The preorder visits the root first and then the left and right subtrees: [root | left | right]. The inorder visits the left first, then the root and then the right: [left | root | right]. For the example tree: preorder [3 | 9 | 2 1 7] and inorder [9 | 3 | 1 2 7].

Binary tree

Splitting the traversals takes 3 steps. The first value of the preorder, 3, is the root. The 3 is found in the inorder: what is to its left, [9], is the left subtree, and what is to the right, [1 2 7], the right one. Since the left has 1 node and the right 3, the preorder splits the same way: [3 | 9 | 2 1 7].

To avoid copying pieces of the lists, 3 indexes are used. i is the root's position in the preorder; m, the root's position in the inorder; and [l, r], the tree's stretch in the inorder. The left subtree has its root at i + 1 and stretch [l, m βˆ’ 1]. The right one has its root at i + 1 + (m βˆ’ l), because the m βˆ’ l nodes of the left must be skipped, and stretch [m + 1, r].

Hash table

In each call you have to find m, the root's position in the inorder. Scanning the inorder every time would cost O(n) per call and O(nΒ²) overall. To avoid that, before starting, a hash table is built that stores each value with its position. That way, finding m costs O(1): with 1,000 nodes, 1,000 instant lookups instead of up to 1 million steps.

Time complexity

Each recursive call creates 1 node in O(1), thanks to the hash table, so the total time is O(n). Memory is O(n) too: the table stores n positions, and in the worst case, if the tree is a single chain like a list, the recursion goes n levels deep. Nodes are created on the way down, and the links between parent and child are made on the way back from each call.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Root, left and right