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)deserialize(data)serializenull
Example 1
serialize: "1,2,N,N,3,4,N,N,5,N,N"
deserialize: the same tree
Example 2
serialize: "N"
deserialize: an empty tree
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
So write that down too. Every time a node has no left child or no right child, write N
Each dashed box NN1,2,N,N,3,4,N,N,5,N,N
Now nothing has to be guessed. Each N1,2,N,N,N1,N,2,N,N
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
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-10split(",")
Reading the string back
How is the tree rebuilt? The same way it was written. Take the next token. If it is N
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
Java Solution
The class has four parts, two for each direction:
: makes aserialize , letsStringBuilder fill it, and drops the comma after the last token. An empty tree becomes justwrite ."N" : the preorder writer. For a missing child it addswrite ; for a node it adds the value and a comma, then writes the left side and then the right side."N," : splits the string at the commas into a queue of tokens, andeserialize namedArrayDeque , and passes it totokens .read : the reader.read removes the next token.tokens.poll() givesN ; a number becomes a node, read withnull , whose left and right sides are read next.Integer.parseInt
The small TreeNodebuildrows
The main
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:
[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"[1, 2, 3, null, null, 4, 5]"N"[]
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""1,N,2,N,N"Integer.parseInt
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
andwrite each deal with the 2n + 1 tokens once, such as the 11 tokens for the 5 nodes of Example 1.read - Space: O(n), because the string and the queue of tokens each hold 2n + 1 tokens, and the chain of unfinished calls to
orwrite grows only as long as the tree is tall.read
Without N