AlgoFrames

Serialization and construction

Serialization turns a tree into a string and back. Watch tokens emitted on the way out and consumed to rebuild the same tree.

Before you start: Recursive problems on trees: height, size, mirror, paths.

The idea

To save a tree in a file or send it over a network, write it as one line of tokens. Reading them back must rebuild the same tree.

Memory addresses mean nothing on another machine. Only values and shape can travel, so the shape has to be written into the tokens.

Intuition

Pre-order values alone are not enough. Both trees read 1, 2, so the reader cannot tell which side 2 is on.

Write # for every missing child. Now the two trees give different strings, and each string fits exactly one tree.

A tree with n nodes has n + 1 missing children. With them written down, every subtree ends at a known token.

Complexity

n nodes give 2n + 1 tokens. Writing and reading each touch every token once, so both are O(n) time.

The string needs O(n) space. The recursion needs O(h) stack, where h is the height: about log2 n for a balanced tree, n for a chain.

Pitfalls

Keep one read position for all calls. If each call keeps its own copy, the right subtree rereads tokens the left one used.

Split the string on commas, not into characters. "12" is one value, and "-5" is one negative value.

Variations

Level order writes rows with # for gaps and drops the # at the end. A sorted array also builds a tree: its middle value is the root.

Code

Pseudocode

serialize(root)
  out ← empty list
  write(node)
    if node is empty: append "#" to out; return
    append node.value to out
    write(node.left)
    write(node.right)
  write(root)
  return out joined with ","

Python

def serialize(root):
    out = []

    def write(node):
        if node is None:
            out.append("#")
            return
        out.append(str(node.val))
        write(node.left)
        write(node.right)

    write(root)
    return ",".join(out)

JavaScript

function serialize(root) {
  const out = [];
  const write = (node) => {
    if (node === null) {
      out.push("#");
      return;
    }
    out.push(String(node.val));
    write(node.left);
    write(node.right);
  };
  write(root);
  return out.join(",");
}

Java

static String serialize(TreeNode root) {
    List<String> out = new ArrayList<>();
    write(root, out);
    return String.join(",", out);
}

static void write(TreeNode node, List<String> out) {
    if (node == null) {
        out.add("#");
        return;
    }
    out.add(String.valueOf(node.val));
    write(node.left, out);
    write(node.right, out);
}

Practice problems (5)

Serialize a tree to a string Warm-up

Write serialize(root), which turns a binary tree into a string. Walk the tree in pre-order: write a node's value, then its left subtree, then its right subtree. Write # for every missing child and join the tokens with commas, with no spaces.

The tree 1 → (2, 3) gives "1,2,#,#,3,#,#". An empty tree gives "#".

Count distinct encodings Standard

Someone saves a tree as its pre-order values only, with no # markers: "1,2,3". How many different binary trees give exactly this string?

Serialize and deserialize Standard

A tree was written with the pre-order format: values and # markers for missing children, joined by commas. For example 1 → (2, 3) is "1,2,#,#,3,#,#".

Write deserialize(data), which rebuilds the tree and returns its root. Together with serialize from the warm-up, this is a full codec: deserialize(serialize(t)) has the same shape and values as t.

Build a balanced BST from a sorted array Standard

nums is sorted in increasing order with no repeats. Build a binary search tree of minimum height that holds every value, and return its root.

Use the middle index (lo + hi) / 2, rounded down, of each range as that subtree's root, so the answer is unique.

Trace deserialize Standard

Rebuild the tree from "5,3,#,4,#,#,8,7,#,#,#". Before each step plays, click the node the next value hangs under.

Related topics

Next on the path: BST: search, insert, min and max