Java Binary Tree Program · OT79
Serialize and Deserialize a Binary Tree in Java
Write the tree in preorder and record every missing child as #. Those markers carry the shape, so reading the tokens back in the same order rebuilds the identical tree.
Problem Statement
Write serialize(root), which turns a binary tree into a string, and deserialize(data), which rebuilds the same tree from that string.
The rebuilt tree must have the same shape and values. An empty tree must round-trip too.
Input/Output Examples
[8, 3, 10, 1, 6, null, 14]Output"8,3,1,#,#,6,#,#,10,#,14,#,#"Explanation: preorder with # for every missing child.[1, null, 2]Output"1,#,2,#,#"Explanation: the # before 2 records the missing left child.[]Output"#"Explanation: a single marker.Visual Explanation
- 8tokens8root
- Left of 8tokens31##6##subtree of 3
- Right of 8tokens10#14##subtree of 10
- Done13 tokens for 6 nodes
#.A tree with n nodes has n + 1 empty child positions, so the string always has 2n + 1 tokens, and reading them in order rebuilds each subtree in the same place.
Approaches
Both approaches produce a string that rebuilds the exact tree. One uses preorder recursion; the other uses a queue.
Approach 1: Preorder With Null Markers (Recommended)
Idea: write the node value, then the left subtree, then the right subtree, with # for null; read tokens back in the same order.
- Serialize: append the value or
#, then recurse left and right. - Deserialize: put the tokens in a queue.
- Read a token; return null for
#, otherwise build the node and read its left and right subtrees.
Time: O(n) · Space: O(n).
Approach 2: Level-Order Format
Idea: write the root, then the two children of every node in queue order, using # for missing children.
- Serialize: BFS, writing both children of each dequeued node.
- Deserialize: create the root, then give each dequeued node the next two tokens as children.
- Enqueue every real child created.
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. The two programs use different string formats (preorder and level order), so their serialized strings differ; both rebuild the original tree, which each program checks.
Approach 1: Preorder With Null Markers (Recommended)
The reader consumes exactly the tokens the writer produced, in the same order, which makes it easy to prove correct.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
public class SerializePreorder {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
// Builds a tree from level-order values, where null means "no child here"
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
TreeNode node = queue.poll();
if (i < values.length && values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
// Preorder with "#" for every missing child: enough information to rebuild the exact shape
static String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
write(root, sb);
return sb.toString();
}
private static void write(TreeNode n, StringBuilder sb) {
if (sb.length() > 0) {
sb.append(',');
}
if (n == null) {
sb.append('#');
return;
}
sb.append(n.val);
write(n.left, sb);
write(n.right, sb);
}
static TreeNode deserialize(String data) {
Deque<String> tokens = new ArrayDeque<>(Arrays.asList(data.split(",")));
return read(tokens);
}
private static TreeNode read(Deque<String> tokens) {
String t = tokens.poll();
if (t.equals("#")) {
return null;
}
TreeNode n = new TreeNode(Integer.parseInt(t));
n.left = read(tokens); // tokens come back in the same preorder
n.right = read(tokens);
return n;
}
static String levelOrderString(TreeNode root) {
List<String> out = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
q.add(root == null ? NULL_NODE : root);
while (!q.isEmpty()) {
TreeNode n = q.poll();
if (n == NULL_NODE) {
out.add("null");
continue;
}
out.add(String.valueOf(n.val));
q.add(n.left == null ? NULL_NODE : n.left);
q.add(n.right == null ? NULL_NODE : n.right);
}
while (!out.isEmpty() && out.get(out.size() - 1).equals("null")) {
out.remove(out.size() - 1);
}
return out.toString();
}
private static final TreeNode NULL_NODE = new TreeNode(0);
public static void main(String[] args) {
Integer[][] trees = {{8, 3, 10, 1, 6, null, 14}, {1, null, 2}, {}};
for (Integer[] t : trees) {
TreeNode root = build(t);
String data = serialize(root);
TreeNode copy = deserialize(data);
System.out.println("\"" + data + "\" -> rebuilt " + levelOrderString(copy)
+ ", same as original: " + levelOrderString(copy).equals(levelOrderString(root)));
}
}
}
"8,3,1,#,#,6,#,#,10,#,14,#,#" -> rebuilt [8, 3, 10, 1, 6, null, 14], same as original: true "1,#,2,#,#" -> rebuilt [1, null, 2], same as original: true "#" -> rebuilt [], same as original: true
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Level-Order Format
Produces the familiar level-order layout used in many problem statements.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class SerializeLevelOrder {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
// Builds a tree from level-order values, where null means "no child here"
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
TreeNode node = queue.poll();
if (i < values.length && values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
// Level order with "#" for missing children; the reader consumes two tokens per node
static String serialize(TreeNode root) {
if (root == null) {
return "#";
}
List<String> out = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
q.add(root);
out.add(String.valueOf(root.val));
while (!q.isEmpty()) {
TreeNode n = q.poll();
for (TreeNode child : new TreeNode[] {n.left, n.right}) {
if (child == null) {
out.add("#");
} else {
out.add(String.valueOf(child.val));
q.add(child);
}
}
}
return String.join(",", out);
}
static TreeNode deserialize(String data) {
String[] t = data.split(",");
if (t[0].equals("#")) {
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(t[0]));
Deque<TreeNode> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty()) {
TreeNode n = q.poll();
if (!t[i].equals("#")) {
n.left = new TreeNode(Integer.parseInt(t[i]));
q.add(n.left);
}
i++;
if (!t[i].equals("#")) {
n.right = new TreeNode(Integer.parseInt(t[i]));
q.add(n.right);
}
i++;
}
return root;
}
static String levelOrderString(TreeNode root) {
List<String> out = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
q.add(root == null ? NULL_NODE : root);
while (!q.isEmpty()) {
TreeNode n = q.poll();
if (n == NULL_NODE) {
out.add("null");
continue;
}
out.add(String.valueOf(n.val));
q.add(n.left == null ? NULL_NODE : n.left);
q.add(n.right == null ? NULL_NODE : n.right);
}
while (!out.isEmpty() && out.get(out.size() - 1).equals("null")) {
out.remove(out.size() - 1);
}
return out.toString();
}
private static final TreeNode NULL_NODE = new TreeNode(0);
public static void main(String[] args) {
Integer[][] trees = {{8, 3, 10, 1, 6, null, 14}, {1, null, 2}, {}};
for (Integer[] t : trees) {
TreeNode root = build(t);
String data = serialize(root);
TreeNode copy = deserialize(data);
System.out.println("\"" + data + "\" -> rebuilt " + levelOrderString(copy)
+ ", same as original: " + levelOrderString(copy).equals(levelOrderString(root)));
}
}
}
"8,3,10,1,6,#,14,#,#,#,#,#,#" -> rebuilt [8, 3, 10, 1, 6, null, 14], same as original: true "1,#,2,#,#" -> rebuilt [1, null, 2], same as original: true "#" -> rebuilt [], same as original: true
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Preorder With Null Markers | O(n) | O(n) |
| Level-Order Format | O(n) | O(n) |
Here n is the number of nodes. Both formats write each node and each empty child once, so they are linear in time and in string length.
Interview Tips and Recommended Approach
- Record the null children. Values alone cannot distinguish different shapes.
- Use a separator that cannot appear in values, such as a comma.
- Test the round trip, including an empty tree and a single node.
- Know the BST shortcut. A BST can be rebuilt from its preorder alone, without null markers.
Recommended Approach: Preorder With Null Markers
Why: the reader is the exact mirror of the writer, which makes the code short and its correctness easy to argue.