Serialize and Deserialize Binary Tree
Pattern: Serialise and deserialise
Write the tree in preorder with a marker such as # for every empty child; that string determines the tree exactly. Read it back with the same preorder: take a token, # means empty, otherwise make a node and read its left and then its right subtree.
The problem
Build a class Codec with serialize(root), which turns a tree into a string, and deserialize(data), which turns
such a string back into the same tree. Any format is allowed; the tests check that deserialize(serialize(t)) prints
the same as t. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Is a preorder of the values enough?
- What makes it enough?
- How do you read it back?
Hints
Brute force, and why it fails
Level order with null markers also works (as LeetCode prints trees), with a queue on both sides.
The key insight
With empty markers, a preorder string has exactly one parse, so writing and reading in the same order round-trips any tree.
Dry run
| text | 1,2,#,#,3,4,#,#,5,#,# |
|---|
Tree [1, 2, 3, null, null, 4, 5]. Preorder with markers: 1, 2, #, #, 3, 4, #, #, 5, #, #.
The plan
serialize(n): n is null -> "#"; else n.val, serialize(n.left), serialize(n.right) joined by commas
deserialize: t = next token; "#" -> null; else node(t) with left = read(), right = read()
Complexity
- Time
O(n)- Space
O(n)
Each node is written and read once.
Edge cases
- Empty tree: "#".
- Negative values.
- A long chain.
I've built my logic, show the code
Java
import java.util.*;
class Codec {
public String serialize(TreeNode root) { // preorder, with # for an empty child
StringBuilder sb = new StringBuilder();
write(root, sb);
return sb.toString();
}
private void write(TreeNode n, StringBuilder sb) {
if (n == null) { sb.append("#,"); return; }
sb.append(n.val).append(',');
write(n.left, sb);
write(n.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) { // the same preorder, read back
String t = tokens.poll();
if (t.equals("#")) return null;
TreeNode n = new TreeNode(Integer.parseInt(t));
n.left = read(tokens);
n.right = read(tokens);
return n;
}
}C++
class Codec {
public:
string serialize(TreeNode* root) { // preorder, with # for an empty child
string out;
write(root, out);
return out;
}
void write(TreeNode* n, string& out) {
if (n == NULL) { out += "#,"; return; }
out += to_string(n->val) + ",";
write(n->left, out);
write(n->right, out);
}
TreeNode* deserialize(string data) {
size_t pos = 0;
return read(data, pos);
}
TreeNode* read(const string& data, size_t& pos) { // the same preorder, read back
size_t comma = data.find(',', pos);
string t = data.substr(pos, comma - pos);
pos = comma + 1;
if (t == "#") return NULL;
TreeNode* n = new TreeNode(stoi(t));
n->left = read(data, pos);
n->right = read(data, pos);
return n;
}
};Python
from lib import TreeNode
class Codec:
def serialize(self, root) -> str: # preorder, with # for an empty child
out = []
def write(n):
if n is None:
out.append("#")
return
out.append(str(n.val))
write(n.left)
write(n.right)
write(root)
return ",".join(out)
def deserialize(self, data: str):
tokens = iter(data.split(","))
def read(): # the same preorder, read back
t = next(tokens)
if t == "#":
return None
n = TreeNode(int(t))
n.left, n.right = read(), read()
return n
return read()Common mistakes
- Leaving out the empty markers.
- Splitting multi-digit values into digits.