Kodewick
Start learning →
Rebuilding a tree from its traversals24 / 52

Rebuilding a tree from its traversals

Lesson 24 of 52 · Part 5 · Trees and heaps · about 18 minutes

Rebuilding a binary tree takes preorder plus inorder: the first preorder value is the root, and its place in inorder splits the left subtree from the right; keeping positions in a dict makes it O(n), while preorder plus postorder is not enough.

To send a tree to someone or save it to a file, you can only write it as a sequence of values. Each of last lesson's four traversals gives one, but one alone can't be drawn back: a preorder of [1, 2] could be 1 with 2 as its left child or 1 with 2 as its right child. Two sequences together are enough: preorder (or postorder) tells you who the root is, and inorder tells you who is on the root's left and who is on its right. It is a favourite exam and interview problem (LeetCode 105), and a fine example of "slicing looks cheap but isn't": the plain version does 15,000 units of work on a tree 100 levels deep, and a small change brings that down to about 300.

Preorder finds the root, inorder splits the sides

Take lesson 1's tree again: preorder [1, 2, 4, 5, 3, 6], inorder [4, 2, 5, 1, 3, 6].

  1. The first in preorder is the root: 1.
  2. Find 1 in inorder: the 4 2 5 on its left is the left subtree and the 3 6 on its right is the right subtree. The left subtree has 3 nodes.
  3. In preorder, the whole left subtree comes right after the root, then the right subtree. So the 3 after 1 in preorder, 2 4 5, are the left subtree's preorder, and the remaining 3 6 are the right subtree's.
  4. Each side is again "one preorder plus one inorder": do the same again.
preorder + inorderpreorderinorder12453642513601234567891011

The first half is preorder, the second inorder. Each round: the first in preorder is the root, the two sides of it in inorder are the two subtrees, and the counts match in both sequences

The same process on the tree: each round takes one root from preorder, and inorder decides which side it hangs on
Choose one

Preorder A B D E C F, inorder D B E A F C. Rebuilding the tree with this stage's method, what is its postorder?

Choose one

Preorder [5, 3, 1, 4, 8, 9], inorder [1, 3, 4, 5, 8, 9]. What is the preorder of the root 5's left subtree?

The plain way: slicing

Turn the four steps above straight into Python, slicing both lists into their left and right halves:

main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def build(pre, ino):8    if not pre:9        return None10    root = TreeNode(pre[0])11    k = ino.index(pre[0])                  # the left subtree has k nodes12    root.left = build(pre[1:k + 1], ino[:k])13    root.right = build(pre[k + 1:], ino[k + 1:])14    return root15 16def postorder(node, out):17    if node:18        postorder(node.left, out)19        postorder(node.right, out)20        out.append(node.val)21    return out22 23root = build([1, 2, 4, 5, 3, 6], [4, 2, 5, 1, 3, 6])24print(root.val, root.left.val, root.right.val, root.right.left)25print(postorder(root, []))
Output
1 2 3 None
[4, 5, 2, 6, 3, 1]

The result is right: postorder [4, 5, 2, 6, 3, 1], the same as last lesson. But every level of calls pays two bills: ino.index scans from the start to the root's position, and the four slices each copy a new list, about 2n items in all. For a balanced tree the n's of each level add up to n log n; for a tree shaped like a line, each level is only 1 smaller than the one above, and they add up to n². Count it:

main.py
1work = 02 3def build(pre, ino):4    global work5    if not pre:6        return None7    k = ino.index(pre[0])8    work += (k + 1) + 2 * (len(pre) - 1)   # index scanned k + 1 items; slices copied about 2(n − 1)9    left = build(pre[1:k + 1], ino[:k])10    right = build(pre[k + 1:], ino[k + 1:])11    return (pre[0], left, right)12 13def balanced_pre(lo, hi, out):             # the preorder of 1..127 built as a balanced tree14    if lo <= hi:15        mid = (lo + hi) // 216        out.append(mid)17        balanced_pre(lo, mid - 1, out)18        balanced_pre(mid + 1, hi, out)19    return out20 21work = 022build(balanced_pre(1, 127, []), list(range(1, 128)))23print("balanced, 127 nodes:", work)24 25work = 026build(list(range(1, 101)), list(range(100, 0, -1)))   # every node has only a left child27print("a line, 100 nodes:", work)
Output
balanced, 127 nodes: 1732
a line, 100 nodes: 14950

The tree shaped like a line has only 100 nodes, yet takes 15,000 units of work: the root is always last in inorder, so index scans the whole sequence, and the slices copy nearly all of it again.

Choose one

In the slicing version, what does the k from k = ino.index(pre[0]) mean?

Choose one

On a tree that is a single line of n nodes (each has only a left child), how much work does the slicing version do in total?

Pass only indexes: O(n)

Both bills can be avoided:

  • ino.index scanning every time → build a dict pos first, value → its index in inorder, and finding the root becomes O(1);
  • slices copying → stop slicing and pass only the bounds in inorder, lo, hi. Preorder needs no slicing either: the roots are taken from it one by one in preorder's own order, so a counter nxt saying who comes next is enough.
main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def build_fast(pre, ino):8    pos = {v: i for i, v in enumerate(ino)}   # value -> index in inorder9    nxt = 0                                   # the next root in preorder10    calls = 011 12    def go(lo, hi):                           # build a subtree from ino[lo..hi]13        nonlocal nxt, calls14        calls += 115        if lo > hi:16            return None17        root = TreeNode(pre[nxt])18        nxt += 119        k = pos[root.val]20        root.left = go(lo, k - 1)             # left first: in preorder the left subtree comes first21        root.right = go(k + 1, hi)22        return root23 24    root = go(0, len(ino) - 1)25    return root, calls26 27def postorder(node, out):28    if node:29        postorder(node.left, out)30        postorder(node.right, out)31        out.append(node.val)32    return out33 34root, calls = build_fast([1, 2, 4, 5, 3, 6], [4, 2, 5, 1, 3, 6])35print(postorder(root, []), calls)36 37root, calls = build_fast(list(range(1, 101)), list(range(100, 0, -1)))38print("a line, 100 nodes:", calls, "calls")
Output
[4, 5, 2, 6, 3, 1] 13
a line, 100 nodes: 201 calls

Each node enters go once and so does each empty place: 2n + 1 calls of O(1) each, plus n steps to build the dict, O(n) in all. Mind the order: the left subtree must be built before the right, because in preorder all of the left subtree's nodes come before the right's, and nxt moves along in that order.

Both versions assume the values are all different; with repeated values, inorder can no longer say exactly where the root is.

VersionFinding the rootSplitting in twoBalanced treeA line
slicing + indexa scan, O(n)copies, O(n)O(n log n)O(n²)
dict + boundsa dict lookup, O(1)pass lo and hi, O(1)O(n)O(n)
Guess the outputA wrong guess is fine

Preorder [3, 9, 20, 15, 7], inorder [9, 3, 15, 20, 7]. Once the tree is built, its postorder is printed. What is it?

1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def build(pre, ino):8    if not pre:9        return None10    root = TreeNode(pre[0])11    k = ino.index(pre[0])12    root.left = build(pre[1:k + 1], ino[:k])13    root.right = build(pre[k + 1:], ino[k + 1:])14    return root15 16def post(node, out):17    if node:18        post(node.left, out)19        post(node.right, out)20        out.append(node.val)21    return out22 23print(post(build([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]), []))
Choose one

In the dict-plus-bounds version, why must the left subtree be built before the right one?

Exercise 1

Inorder plus postorder

Complete build(ino, post): rebuild the binary tree from inorder and postorder. The last in postorder is the root; taking roots from the back, you meet the right subtree's root first, so build the right subtree first.

It should print
[3, 9, 20, 15, 7]
[1, 2, 4, 5, 3, 6]
[]
exercise1.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def build(ino, post):8    pos = {v: i for i, v in enumerate(ino)}9    nxt = len(post) - 1                   # the next root in postorder (from the back)10 11    def go(lo, hi):12        nonlocal nxt13        # lo > hi returns None; otherwise post[nxt] is the root, nxt goes down by one, then build both sides14        return None15 16    return go(0, len(ino) - 1)17 18def pre(node):19    return [node.val] + pre(node.left) + pre(node.right) if node else []20 21print(pre(build([9, 3, 15, 20, 7], [9, 15, 7, 20, 3])))22print(pre(build([4, 2, 5, 1, 3, 6], [4, 5, 2, 6, 3, 1])))23print(pre(build([], [])))
Output
Press Run or Ctrl+Enter
Exercise 2

Postorder without building the tree

Complete to_post(pre, ino): given preorder and inorder, return postorder without making a single node. It is still "preorder finds the root, inorder splits the sides", only instead of making a node you append the root to out once both sides are done.

It should print
[4, 5, 2, 6, 3, 1]
[9, 15, 7, 20, 3]
[3, 2, 1]
exercise2.py
1def to_post(pre, ino):2    pos = {v: i for i, v in enumerate(ino)}3    nxt = 04    out = []5 6    def go(lo, hi):7        nonlocal nxt8        # lo > hi returns at once; otherwise pre[nxt] is the root: do the left, then the right, then put the root in out9        return10 11    go(0, len(ino) - 1)12    return out13 14print(to_post([1, 2, 4, 5, 3, 6], [4, 2, 5, 1, 3, 6]))15print(to_post([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]))16print(to_post([1, 2, 3], [3, 2, 1]))
Output
Press Run or Ctrl+Enter

Why preorder plus postorder is not enough

Preorder and postorder both tell you only who the root is; neither says which side of the root the other nodes are on. The smallest counterexample has just two nodes:

main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def pre(node):8    return [node.val] + pre(node.left) + pre(node.right) if node else []9 10def ino(node):11    return ino(node.left) + [node.val] + ino(node.right) if node else []12 13def post(node):14    return post(node.left) + post(node.right) + [node.val] if node else []15 16a = TreeNode(1, TreeNode(2), None)       # 2 is the left child17b = TreeNode(1, None, TreeNode(2))       # 2 is the right child18print("preorder ", pre(a), pre(b))19print("postorder", post(a), post(b))20print("inorder  ", ino(a), ino(b))
Output
preorder  [1, 2] [1, 2]
postorder [2, 1] [2, 1]
inorder   [2, 1] [1, 2]

Two different trees with the same preorder and the same postorder; only inorder tells them apart: when a node has a single child, neither preorder nor postorder can say whether it is on the left or the right. So rebuilding always takes inorder plus one more:

The two sequencesUnique tree?Where the root comes from
preorder + inorderyesthe first in preorder
postorder + inorderyesthe last in postorder
level order + inorderyesthe first in level order
preorder + postordernot alwaysonly when every node has 0 or 2 children

In interviews: once it is written, state the cost: dict plus bounds is O(n) time and O(n) space (the dict plus the recursion stack). "Why build the left subtree first?", "What if values repeat?" and "Would preorder plus postorder do?" are the usual follow-ups, all answered in this lesson.

Choose one

Which pair of traversals does not always pin down a single binary tree?

Choose one

Inorder [2, 1, 3], postorder [2, 3, 1]. What is this tree's preorder?

How you write it at work

When you really need to save a tree and read it back (LeetCode 297, "serialize"), at work you don't save two traversals; you save one preorder with markers for the gaps: every None is written too, as #. The markers supply the "which side" information, so one sequence is enough. Reading it back takes the items one by one in order with iter and next:

main.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def dumps(node):8    if node is None:9        return ["#"]10    return [str(node.val)] + dumps(node.left) + dumps(node.right)11 12def loads(tokens):13    it = iter(tokens)14    def go():15        t = next(it)16        if t == "#":17            return None18        return TreeNode(int(t), go(), go())   # arguments run left to right: left first19    return go()20 21root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),22                TreeNode(3, None, TreeNode(6)))23s = ",".join(dumps(root))24print(s)25back = loads(s.split(","))26print(",".join(dumps(back)) == s, back.right.right.val)
Output
1,2,4,#,#,5,#,#,3,#,6,#,#
True 6
  • When the data is nested dicts and lists already, use json.dumps directly; only your own TreeNode needs converting like this.
  • The dumps above builds new lists at every level, which is O(n²) for a tree shaped like a line; for large trees, append into one shared list instead.
  • When a problem hands you two traversals to rebuild from, write the dict-plus-bounds version by default.
Guess the outputA wrong guess is fine

Preorder with markers for empty spots: 1 has only a right child, 2. What does it print?

1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def dumps(node):8    if node is None:9        return ["#"]10    return [str(node.val)] + dumps(node.left) + dumps(node.right)11 12print(",".join(dumps(TreeNode(1, None, TreeNode(2)))))

Summary

Take-away

Preorder finds the root, inorder splits the sides

  • The first in preorder (the last in postorder) is the root; left of it in inorder is the left subtree, right of it the right
  • The slicing version is simple, but index plus copying is O(n) per level: O(n²) for a tree shaped like a line
  • A dict of inorder positions + passing lo and hi + a counter for roots: O(n); preorder builds left first, postorder right first
  • Preorder plus postorder can't tell which side a single child is on; you need inorder
  • To save a tree: one preorder with # markers for the gaps is enough
1pos = {v: i for i, v in enumerate(ino)}2def go(lo, hi):              # nxt: the next root in preorder3    if lo > hi: return None4    root = TreeNode(pre[nxt]); nxt += 15    k = pos[root.val]6    root.left, root.right = go(lo, k - 1), go(k + 1, hi)