Serialize and Deserialize Binary Tree

Turn a binary tree into a string, and rebuild the same tree from that string.

Write two methods for a binary tree of integers. serialize(root) turns the tree into a string, and deserialize(data) turns that string back into a tree with the same values in the same places. Any string format is allowed, as long as deserializing the string from serialize gives back the original tree. In the examples, a tree is listed row by row from the top, left to right, with null where a child is missing.

Example 1
Input: root = [1, 2, 3, null, null, 4, 5]
serialize: "1,2,N,N,3,4,N,N,5,N,N"
deserialize: the same tree
Example 2
Input: root = []
serialize: "N"
deserialize: an empty tree
Solution

The Idea

A tree in a running program is a set of objects that point at each other. To save it in a file or send it to another program, it has to become plain text, and the other side has to build the same tree again from that text. Turning a structure into text is called serializing, and building it back is deserializing.

Look at Example 1. Each value sits in a node, and the node at the top, called the root, holds 1. The nodes hanging just below a node are its children. The left child of 1 is 2, which has no children of its own, and the right child of 1 is 3, whose children are 4 and 5. Suppose we write the root first, then everything on its left side, then everything on its right side. That gives 1, 2, 3, 4, 5. Does that list say where each value belongs?

Not on its own. Take a smaller tree: 1 with a single child, 2. If 2 is the left child, the list is 1, 2. If 2 is the right child, the list is still 1, 2. Two different trees give the same list, so deserialize cannot know which one to build. The list is missing one piece of information: where a node has no child.

So write that down too. Every time a node has no left child or no right child, write N in its place. Look at the picture below.

The tree of Example 1 with every missing child drawn as a dashed box N. Small orange numbers give the order of writing: 1, 2, N, N, 3, 4, N, N, 5, N, N, which is the string shown in the bottom row.

Each dashed box N is a missing child, and the small orange number beside each item is its place in the order of writing. Node 1 comes first, then 2, then the two missing children of 2, numbered 3 and 4. Only then does the writing move to node 3, its left child 4 with two N boxes, and its right child 5 with two more. The bottom row, "the string, written in that order", is the result: 1,2,N,N,3,4,N,N,5,N,N.

Now nothing has to be guessed. Each N says that a branch stops there. After 2, N, N, node 2 is complete, so the next value, 3, can only be the right child of 1. The two small trees also get different strings now: 1,2,N,N,N when 2 is on the left and 1,N,2,N,N when it is on the right.

Solution Approach

The code needs three choices: the order in which nodes are written, how the values are kept apart in the string, and how the string is read back. A string written row by row is an optional alternative.

The order of writing

Which order did the picture use? Each node is written before everything below it, then its left side in full, then its right side in full. Visiting a tree in this order, node first, is called preorder. It suits rebuilding, because every node is read before its children, so the node exists by the time its children need a parent.

Preorder is easy to write as a method that calls itself. For a missing child it writes N. For a real node it writes the value, then calls itself on the left child, then on the right child. Each call finishes its whole side of the tree before the next call starts.

Keeping the values apart

Why does the string need commas? Values can have several digits or a minus sign. Without a separator, a node holding 305 would read as 3, 0 and 5, three separate nodes. A comma after each value keeps 305 whole, and a negative value such as -10 too, and split(",") cuts the string back into its pieces, called tokens.

Reading the string back

How is the tree rebuilt? The same way it was written. Take the next token. If it is N, there is no node here. Otherwise make a node with that value, build its left side from the tokens that follow, then build its right side.

The reading method calls itself too. The tokens wait in one queue, a line where they come out in the order they went in, and all these calls share it. Each call removes the tokens it uses. So when the left side of a node is finished, the next token in the queue is the first one of its right side. With the Example 1 string, the root takes 1, its left side takes 2, N, N, and its right side takes the rest, starting at 3.

Optional: writing row by row

The row-by-row form used in the examples can also be the string. Nodes are written level by level, using a queue of nodes waiting to be visited, with N for each missing child. It takes the same time, but both methods need that queue of nodes, while in preorder the method calling itself keeps track of where it is in the tree.

Java Solution

The class has four parts, two for each direction:

  • serialize: makes a StringBuilder, lets write fill it, and drops the comma after the last token. An empty tree becomes just "N".
  • write: the preorder writer. For a missing child it adds "N,"; for a node it adds the value and a comma, then writes the left side and then the right side.
  • deserialize: splits the string at the commas into a queue of tokens, an ArrayDeque named tokens, and passes it to read.
  • read: the reader. tokens.poll() removes the next token. N gives null; a number becomes a node, read with Integer.parseInt, whose left and right sides are read next.

The small TreeNode class holds a value and two children. The helpers build and rows turn the row-by-row form into a tree and back, so the input and output read like the examples.

The main method takes five trees: the two examples, the tree 1 with 2 first as its left child and then as its right child, and a tree with a negative and a three-digit value. For each one it prints the tree, its string, and the tree read back from that string.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class SerializeDeserializeBinaryTree {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    // Preorder, with "N" for every missing child.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        write(root, sb);
        return sb.substring(0, sb.length() - 1);   // drop the trailing comma
    }

    private void write(TreeNode node, StringBuilder sb) {
        if (node == null) {
            sb.append("N,");                       // a missing child
            return;
        }
        sb.append(node.val).append(',');
        write(node.left, sb);
        write(node.right, sb);
    }

    public TreeNode deserialize(String data) {
        Deque<String> tokens = new ArrayDeque<>(Arrays.asList(data.split(",")));
        return read(tokens);
    }

    private TreeNode read(Deque<String> tokens) {
        String t = tokens.poll();                  // the next token, in written order
        if (t.equals("N")) {
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(t));
        node.left = read(tokens);                  // uses up the whole left subtree
        node.right = read(tokens);
        return node;
    }

    // Helpers: build a tree from the row-by-row form and print it back in that form.
    static TreeNode build(Integer[] rows) {
        if (rows.length == 0 || rows[0] == null) return null;
        TreeNode root = new TreeNode(rows[0]);
        Queue<TreeNode> q = new LinkedList<>(List.of(root));
        for (int i = 1; i < rows.length; i += 2) {
            TreeNode p = q.poll();
            if (rows[i] != null) q.add(p.left = new TreeNode(rows[i]));
            if (i + 1 < rows.length && rows[i + 1] != null) {
                q.add(p.right = new TreeNode(rows[i + 1]));
            }
        }
        return root;
    }

    static String rows(TreeNode root) {
        List<Integer> out = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        while (!q.isEmpty()) {
            TreeNode n = q.poll();
            out.add(n == null ? null : n.val);
            if (n != null) { q.add(n.left); q.add(n.right); }
        }
        while (!out.isEmpty() && out.get(out.size() - 1) == null) out.remove(out.size() - 1);
        return out.toString();
    }

    public static void main(String[] args) {
        SerializeDeserializeBinaryTree codec = new SerializeDeserializeBinaryTree();
        Integer[][] inputs = {
            {1, 2, 3, null, null, 4, 5},           // Example 1
            {},                                    // Example 2: empty tree
            {1, 2},                                // 2 as the left child
            {1, null, 2},                          // 2 as the right child
            {-10, null, 20, 305}                   // negative and multi-digit values
        };
        for (Integer[] in : inputs) {
            String s = codec.serialize(build(in));
            TreeNode back = codec.deserialize(s);
            System.out.println(Arrays.toString(in) + " -> \"" + s + "\" -> " + rows(back));
        }
    }
}

Running it prints:

Output
[1, 2, 3, null, null, 4, 5] -> "1,2,N,N,3,4,N,N,5,N,N" -> [1, 2, 3, null, null, 4, 5]
[] -> "N" -> []
[1, 2] -> "1,2,N,N,N" -> [1, 2]
[1, null, 2] -> "1,N,2,N,N" -> [1, null, 2]
[-10, null, 20, 305] -> "-10,N,20,305,N,N,N" -> [-10, null, 20, 305]

Look at the first line: the tree of Example 1 becomes "1,2,N,N,3,4,N,N,5,N,N", the bottom row of the picture, and reading that string back gives [1, 2, 3, null, null, 4, 5] again. The empty tree of Example 2 becomes a single "N" and reads back as [].

The third and fourth lines are the small tree 1 with a single child 2, first on the left and then on the right. Their strings, "1,2,N,N,N" and "1,N,2,N,N", differ only in where the markers sit, and each reads back with 2 on its own side. In the last line, the commas keep 305 as one token and Integer.parseInt reads the minus sign of -10, so that tree comes back unchanged too.

Complexity

Both directions handle every node once and every missing child once, and a tree of n nodes has n + 1 missing children.

  • Time: O(n) for each method, because write and read each deal with the 2n + 1 tokens once, such as the 11 tokens for the 5 nodes of Example 1.
  • Space: O(n), because the string and the queue of tokens each hold 2n + 1 tokens, and the chain of unfinished calls to write or read grows only as long as the tree is tall.

Without N markers, a tree whose values are all different can still be rebuilt from two lists in different orders, as in Construct from Preorder and Inorder.