Algo-Sim › Binary Trees & BST
Serialize and Deserialize Binary Tree
Hard · Binary Trees & BST · step through it in Java, Python and C++ on your own input
Write the tree in preorder with "#" for null children, then read the tokens back in the same order to rebuild it.
Problem
Design two functions: serialize turns a binary tree into a string, and deserialize turns that string back into an identical tree. Any format works as long as the round trip is exact.
Constraints
- 0 ≤ number of nodes ≤ 10⁴
- -1000 ≤ Node.val ≤ 1000
- Null children must be recorded, or different shapes collide
Edge cases to test
- Empty tree
- Negative and multi-digit values
- A skewed tree
Follow-up questions
- Why mark nulls?
- Preorder alone is ambiguous; with null markers each token sequence describes exactly one tree.
- What changes for a BST?
- No null markers are needed: preorder plus the BST bounds rebuilds it in O(n) (LC 449).
Solution
Java
public class Codec {
public String serialize(TreeNode root) {
List<String> out = new ArrayList<>();
write(root, out);
return String.join(",", out);
}
private 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);
}
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();
if (t.equals("#")) return null;
TreeNode node = new TreeNode(Integer.parseInt(t));
node.left = read(tokens);
node.right = read(tokens);
return node;
}
}Python
class Codec:
def serialize(self, root):
out = []
def write(node):
if not node:
out.append("#")
return
out.append(str(node.val))
write(node.left)
write(node.right)
write(root)
return ",".join(out)
def deserialize(self, data):
tokens = iter(data.split(","))
def read():
t = next(tokens)
if t == "#":
return None
node = TreeNode(int(t))
node.left = read()
node.right = read()
return node
return read()C++
#include <bits/stdc++.h>
using namespace std;
class Codec {
public:
string serialize(TreeNode *root) {
vector<string> out = {};
write(root, out);
string result;
for (const auto &token : out) {
if (!result.empty())
result += ',';
result += token;
}
return result;
}
void write(TreeNode *node, vector<string> &out) {
if (node == nullptr) {
out.push_back("#");
return;
}
out.push_back(to_string(node->val));
write(node->left, out);
write(node->right, out);
}
TreeNode *deserialize(string &data) {
deque<string> tokens;
string token;
istringstream stream(data);
while (getline(stream, token, ','))
tokens.push_back(token);
return read(tokens);
}
TreeNode *read(deque<string> &tokens) {
string t = tokens.front();
tokens.pop_front();
if ((t == "#"))
return nullptr;
TreeNode *node = new TreeNode(stoi(t));
node->left = read(tokens);
node->right = read(tokens);
return node;
}
};
More Binary Trees & BST problems
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)