Python 3D Academyবাংলা

Rebuilding and saving trees: from two walks, and to a string

🌍 In real life. A school's house teams are organised as a tree: a captain, two vice-captains, and so on. To send the whole structure to another school by SMS you need it as a line of text, and the other school must be able to draw exactly the same tree from that text.

There are two classic ways. You can send two walks of the tree, its preorder and inorder (Lesson 47.2), from which the tree can be rebuilt (LeetCode 105). Or you can send one preorder walk with a mark for every missing child: serializing (LeetCode 297).

The idea in one sentence: in preorder the first value is always the root, and in inorder the root splits the values into its left and right subtrees, so the two walks together rebuild the tree; and a preorder walk that writes # for every empty child is enough on its own, because the marks say exactly where each subtree ends.

Its words:

  • preorder: node, then left subtree, then right subtree; inorder: left subtree, node, right subtree
  • serialize: turn a structure into text; deserialize: turn the text back into the same structure
  • null marker: #, written where a child is missing

Step by step, rebuilding from preorder [3, 9, 20, 15, 7] and inorder [9, 3, 15, 20, 7]:

  1. Preorder starts with 3: 3 is the root.
  2. In inorder, 3 has [9] on its left and [15, 20, 7] on its right.
  3. Next in preorder is 9: the root of the left part, which has nothing else.
  4. Next is 20: the root of the right part, splitting it into [15] and [7].

The two walks of that tree, one after the other:

class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def build(preorder, inorder):
    where = {v: i for i, v in enumerate(inorder)}   # each value's place in inorder
    pos = 0                                          # the next root in preorder

    def make(lo, hi):                               # the subtree of inorder[lo:hi]
        nonlocal pos
        if lo == hi:
            return None
        val = preorder[pos]
        pos += 1
        mid = where[val]
        left = make(lo, mid)                        # everything left of val in inorder
        right = make(mid + 1, hi)                   # everything right of it
        return Node(val, left, right)

    return make(0, len(inorder))


root = build([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])
print(root.val, root.left.val, root.right.val, root.right.left.val, root.right.right.val)
`where` finds each value's place in inorder in O(1), and `pos` walks preorder once.

Why the order of the two calls matters. Preorder lists the whole left subtree before the right one, so make must build the left side first: it uses up exactly the left subtree's values from preorder, and then pos points at the right subtree's root.

Saving a tree as text. One preorder walk is not enough on its own: [1, 2] could be 2 as the left child of 1, or as the right one. Writing # for each missing child removes the doubt: 1,2,#,#,# and 1,#,2,#,# are different. To read it back, take the parts one at a time: a number makes a node, then its left subtree, then its right subtree; # means "nothing here". The marks tell each call exactly when to stop.

What it costs, by counting. Rebuilding visits each value once and finds its inorder place in O(1) thanks to the dict: O(n) (searching inorder with index() each time would be O(n²)). Serializing and deserializing each touch every node and every # once: O(n) time, and the text is about 2n + 1 parts. All need O(h) for the recursion.

class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def serialize(node):
    if node is None:
        return "#"
    return f"{node.val},{serialize(node.left)},{serialize(node.right)}"


def deserialize(text):
    parts = iter(text.split(","))

    def make():
        part = next(parts)
        if part == "#":
            return None
        node = Node(int(part))
        node.left = make()
        node.right = make()
        return node

    return make()


tree = Node(1, Node(2), Node(3, Node(4), Node(5)))
text = serialize(tree)
print(text)
copy = deserialize(text)
print(serialize(copy) == text, copy.right.left.val)
print(serialize(Node(1, Node(2))), serialize(Node(1, None, Node(2))))
The two-node trees in the last line look alike as plain walks, but their serialized texts differ.

Mistakes and edge cases.

  • Building the right side first. pos then hands the left subtree's values to the right side, and the walk runs off the end of preorder: IndexError: list index out of range.
  • Repeated values. where maps each value to one place, so preorder + inorder can only rebuild trees whose values are all different. Serializing with # has no such limit.
  • Searching inorder each time. inorder.index(val) inside make is a hidden loop: O(n²) on a long, thin tree.
  • Leaving out the null markers. Without #, deserializing can't tell where a subtree ends; the tree comes back wrong.
  • Commas inside values. If the values are text, a value containing , breaks split(","); pick a separator that can't appear, or escape it, or use JSON.

Quiz

  1. What does this print?

    class Node:
        def __init__(self, val, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right
    
    
    def serialize(node):
        if node is None:
            return "#"
        return f"{node.val},{serialize(node.left)},{serialize(node.right)}"
    
    
    print(serialize(Node(5, None, Node(8, Node(6)))))
  2. Preorder is [4, 2, 1, 3] and inorder is [1, 2, 3, 4]. What is the root's right child?

    • There is none: everything is left of 4
    • 3
    • 2
  3. Why does a serialized tree need a marker like # for missing children?

    • Without it, one walk can't say where a subtree ends, so different trees give the same text
    • To make the text shorter
    • Python can't split text without it
  4. build([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]) stops with IndexError: list index out of range. Which line is wrong?

    def build(preorder, inorder):
        where = {v: i for i, v in enumerate(inorder)}
        pos = 0
    
        def make(lo, hi):
            nonlocal pos
            if lo == hi:
                return None
            val = preorder[pos]
            pos += 1
            mid = where[val]
            right = make(mid + 1, hi)
            left = make(lo, mid)
            return Node(val, left, right)
    
        return make(0, len(inorder))

Coding tasks

  1. Write build(preorder, inorder): rebuild the tree (all values different) and return its root, in O(n).

  2. Write serialize(node) (preorder, values and # joined by commas) and deserialize(text), so that deserialize(serialize(tree)) gives back the same tree.