297. Serialize and Deserialize Binary Tree
Asked at 23Microsoft59Amazon56Apple51Meta47Bloomberg44Google38PhonePe53Yahoo100Hive87Quora78Nutanix71LinkedIn64Uber60Citadel57TikTok56General Motors52DoorDash45Flipkart43PayPal42Nvidia39tcs36Atlassian34Oracle27
Problem
Design a Codec whose serialize(root) turns a binary tree into a string and deserialize(data) rebuilds exactly the same tree from that string. Any format works as long as the round trip is exact.
Example: deserialize(serialize([1,2,3,null,null,4,5])) → [1,2,3,null,null,4,5]
Constraints: up to 10⁴ nodes; values in [−1000, 1000].
Preorder with explicit null markers (#) uniquely identifies a tree. Deserialize by consuming tokens in the same preorder.
1
/ \ "1,2,#,#,3,4,#,#,5,#,#"
2 3
/ \
4 5
Complexity: O(n) both ways.
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
out = []
def dfs(node):
if not node:
out.append("#")
return
out.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ",".join(out)
def deserialize(self, data: str) -> Optional[TreeNode]:
it = iter(data.split(","))
def build():
v = next(it)
if v == "#":
return None
node = TreeNode(int(v))
node.left = build()
node.right = build()
return node
return build()
c = Codec()
t = make_tree([1, 2, 3, None, None, 4, 5])
assert c.serialize(t) == "1,2,#,#,3,4,#,#,5,#,#"
assert tree_vals(c.deserialize(c.serialize(t))) == [1, 2, 3, None, None, 4, 5]
assert c.deserialize(c.serialize(None)) is None
class Codec {
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
ser(root, sb);
return sb.substring(0, sb.length() - 1);
}
private void ser(TreeNode n, StringBuilder sb) {
if (n == null) { sb.append("#,"); return; }
sb.append(n.val).append(',');
ser(n.left, sb);
ser(n.right, sb);
}
public TreeNode deserialize(String data) {
return des(new ArrayDeque<>(Arrays.asList(data.split(","))));
}
private TreeNode des(Deque<String> q) {
String v = q.poll();
if (v.equals("#")) return null;
TreeNode n = new TreeNode(Integer.parseInt(v));
n.left = des(q);
n.right = des(q);
return n;
}
}
type Codec struct{}
func Constructor() Codec {
return Codec{}
}
// serialize writes the preorder with "#" for missing children.
func (this *Codec) serialize(root *TreeNode) string {
out := []string{}
var dfs func(*TreeNode)
dfs = func(node *TreeNode) {
if node == nil {
out = append(out, "#")
return
}
out = append(out, strconv.Itoa(node.Val))
dfs(node.Left)
dfs(node.Right)
}
dfs(root)
return strings.Join(out, ",")
}
func (this *Codec) deserialize(data string) *TreeNode {
vals, i := strings.Split(data, ","), 0
var build func() *TreeNode
build = func() *TreeNode {
v := vals[i]
i++
if v == "#" {
return nil
}
n, _ := strconv.Atoi(v)
node := &TreeNode{Val: n}
node.Left = build()
node.Right = build()
return node
}
return build()
}