Which traversal pairs define a unique tree

Video lessonComing soon

1 A puzzle: draw the tree from one list

The lesson on traversal orders walked our running tree in three orders. Now we go the other way. A tree's preorder is 1 2 4 5 3 6. Can we draw the tree?

We can draw one, but not the one. Both of these trees have exactly that preorder:

425136
Our tree. Inorder: 4 2 5 1 3 6
421356
Another. Inorder: 4 2 1 3 5 6

Preorder says which node comes first, but not where each node hangs. The second tree moves 5 up and hangs 3 under it, and the preorder does not change. One order loses the shape. Inorder alone loses it too, as the next section shows.

Their inorders differ, though. This lesson finds which pairs of orders fix the tree, and rebuilds a tree from one.

2 What each order tells us

Picture the sun straight above the tree. Each node casts its shadow on the ground, in its own column. Reading the shadows from left to right gives 4 2 5 1 3 6. That is the inorder.

425136
425136
The shadow is the inorder. 1 splits it in two

The shadow keeps left and right. Everything left of 1's shadow is 1's left subtree, and everything right of it is the right subtree. But the shadow has no heights. This tree casts the very same shadow:

425136
Same inorder, 4 2 5 1 3 6, with 3 on top

So inorder needs a partner that says which node is on top. Preorder and postorder both do:

OrderWhat it tells us
PreorderThe first value is the root
PostorderThe last value is the root
InorderWhich values are left of a node, and which are right

Together they split the tree in two. The root comes from preorder, and inorder splits the rest into a left part and a right part. Each part is a smaller tree, and we have both its orders. So we ask the same question again on each part, until a part is empty.

3 Rebuilding our tree

Here is our tree rebuilt from preorder 1 2 4 5 3 6 and inorder 4 2 5 1 3 6. Blue marks the left part and orange the right part. Faded values belong to parts already done.

Preorder + inorder → tree
124536root
preorder
425136root
inorder
1
1 is first in preorder, so it is the root

The key step is step 3. Inorder told us the left part has 3 values. Preorder lists the root, then the whole left subtree, then the whole right subtree. So the left part in preorder is the 3 values right after the root, and the rest is the right part. Both lists split into the same pieces, with the same sizes.

Step 6 shows an empty part. Nothing in inorder sits left of 3, so 3 has no left child. An empty part becomes null.

4 The split as index arithmetic

In code, we do not copy the parts out. We pass index ranges into the two original arrays. A call gets three numbers:

  • preStart: where this part's preorder begins. Its root is preorder[preStart].
  • inStart and inEnd: this part's range in inorder.

The call finds the root in inorder at rootIndex. The values from inStart up to just before rootIndex are the left part, so:

leftSize = rootIndex − inStart

The left part's preorder starts just after the root, at preStart + 1. The right part's preorder skips the root and the whole left part, so it starts at preStart + 1 + leftSize. In inorder, the left part is inStart to rootIndex - 1, and the right part is rootIndex + 1 to inEnd. A range with inStart > inEnd is empty, and the call returns null.

Here is every call that makes a node, on our tree. A child call is written as (preStart, inorder range):

preStartinorder rangerootrootIndexleftSizeleft callright call
00..5133(1, 0..2)(4, 4..5)
10..2211(2, 0..0)(3, 2..2)
20..0400emptyempty
32..2520emptyempty
44..5340empty(5, 5..5)
55..5650emptyempty

The first row is steps 1 to 3 of the drawing. The right call starts at 4 because the root takes one place and the left part takes three.

Each call must find its root in inorder. A loop that searches for it costs up to n steps per call. Instead, we build a map from each value to its index in inorder once, before the first call. Then every lookup is one step. This only works when the values are distinct, so that each value has one place in inorder. The problems promise it.

5 buildTree in code

The main function fills the map and makes the first call on the whole range. The helper build follows the table: make the root, find it, work out leftSize, then build the left and right children.

On our lists, the function returns the tree [1,2,3,4,5,null,6]. On the second tree's lists from section 1, preorder 1 2 4 5 3 6 and inorder 4 2 1 3 5 6, it returns [1,2,5,4,null,3,6]. Only the inorder changed, and it moved the split.

C++

The map is a member. inorderIndex lives in the class, so build reads it without taking it as a parameter. The vector goes down by reference, so no call copies it.

The map is a field. build reads inorderIndex without taking it as a parameter. get returns an Integer, which Java turns into an int for rootIndex.

A nested function. build sits inside the method, so it reads preorder and inorder_index without taking them as parameters. It passes indexes, not slices such as preorder[1:4], because a slice copies the values.

An arrow function inside. build is defined inside buildTree, so it reads preorder and inorderIndex directly. It passes indexes, not slice copies.

Declare, then assign. var build func(...) comes first, so the function literal can call build inside itself. A plain build := func... cannot refer to itself.

Signed indexes. The ranges are i32, not usize, because root_index - 1 is -1 when the root is first in its range. A usize would underflow there. Only pre_start turns into a usize, to index preorder.

The map is a field. Build reads inorderIndex without taking it as a parameter. A missing child is null.

Time. Filling the map is one pass. Each node then takes one call with a map lookup and a little arithmetic, and each empty part takes one call that returns at once. So the whole build is O(n).

Space. The map holds n entries, O(n). The call stack holds one path from the root, so it grows to the tree's height h: about 17 calls for a balanced tree of 10⁵ nodes, and up to 10⁵ for a chain.

6 The other pairs

Inorder + postorder works the same way. Postorder writes a node last, so the root of a part is its last value. Inorder gives leftSize as before. In postorder, the left part comes first with leftSize values, the right part follows, and the root closes the part.

Some solutions read postorder with one pointer, moving from the back. Just before the root sits the right subtree, not the left. So that version must build the right child first.

Preorder + postorder has no shadow. Both lists say which node is on top, and neither says which side a child is on. Our tree and one with 6 moved to 3's left have the same two lists:

425136
6 on the right
425163
6 on the left

Both have preorder 1 2 4 5 3 6 and postorder 4 5 2 6 3 1. Node 3 has one child, and nothing tells its side.

The pair does work when every node has 0 or 2 children. Then the value right after the root in preorder must be the left child. We find it in postorder, and everything up to it is the left subtree.

Orders given (distinct values)One tree?
One order aloneNo
Preorder + inorderYes
Inorder + postorderYes
Preorder + postorderOnly if every node has 0 or 2 children
Preorder with the nulls writtenYes, next section

A binary search tree needs only its preorder. Its inorder is its values in sorted order, so the shadow comes free. The next topic, on BSTs, uses this.

7 Writing the nulls: one order is enough

A problem can also ask us to turn a tree into a string and back. This is serializing a tree. We choose the format, so we can write down the empty children too. Here # marks a null:

1 2 4 # # 5 # # 3 # 6 # #

This is preorder with every null written. A tree of 6 nodes has 7 empty children, so the string has 13 tokens. The # marks tell where each subtree ends. That was what the shadow told us before, so now one order is enough.

Two trees from the traversal orders lesson, 2 as the left child of 1 or as the right child, share the preorder 1 2. With the nulls written, they differ:

21
1 2 # # #
12
1 # 2 # #

To read the string back, we take the tokens one at a time, in order:

  1. Take the next token. If it is #, this subtree is empty: return null.
  2. Otherwise, make a node with that value.
  3. Read its left subtree, then its right subtree, from the same tokens.

On 1 # 2 # #, node 1 reads # as its left child. Its right subtree starts at 2, and 2 reads two # marks. Every token is read once, so both directions take O(n) time.

8 Mistakes, and when to use this

  • Off by one in the right part's start. Writing preStart + leftSize forgets the root. On our lists, 2's right child comes out as 4 a second time. From there the ranges stop shrinking, and the recursion runs until it gets a Runtime Error.
  • Searching inorder with a loop. On a chain of 10⁵ nodes, each search can scan most of its range. That adds up to around 5 × 10⁹ steps, and it gets TLE. Copying the parts into new arrays at every call costs the same.
  • Duplicate values. Preorder 2 2 and inorder 2 2 fit a 2 with a left child 2 and a 2 with a right child 2. The map also keeps only one index per value. Check that the problem promises distinct values.
  • Left before right when reading postorder from the back. On our tree, the value before the root 1 is 3. Building the left child first makes 3 the root of the left part, though 3 is on the right.

The sign for this subtopic is a problem that gives traversal orders, or a string, and wants the tree back.

Before rebuilding a tree, find the list that names each part's root and the list that splits left from right. If no list splits the sides, the tree may not be unique.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.