Serialize a binary tree
Serialize a binary tree into a comma-separated preorder string that includes markers for missing children.
Course progress
Problem 85 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
tree = 1 with left 2 and right 3; node 3 has left 4
Expected output
1,2,#,#,3,4,#,#,#
What is happening?
Preorder writes each node before its children and # for nulls, preserving both values and shape as 1,2,#,#,3,4,#,#,#.
Solution strategy
Build the right mental model
Write the current value before both subtrees and write # for each null child so the original shape is preserved.
Core concepts
binary tree · preorder traversal
Complexity
Time O(n), space O(n) for output plus O(h) call-stack space.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for serialize-binary-tree
using System;
using System.Collections.Generic;
class Program
{
class Node
{
public int Value { get; private set; }
public Node Left { get; set; }
public Node Right { get; set; }
public Node(int value) { Value = value; }
}
static void Serialize(Node node, List<string> values)
{
if (node == null) { values.Add("#"); return; }
values.Add(node.Value.ToString());
Serialize(node.Left, values);
Serialize(node.Right, values);
}
static void Main()
{
Node root = new Node(1) {
Left = new Node(2), Right = new Node(3) { Left = new Node(4) }
};
var values = new List<string>();
Serialize(root, values);
Console.WriteLine(string.Join(",", values));
}
}Knowledge check
Questions students often ask
What is the main idea behind serialize a binary tree?
Write the current value before both subtrees and write # for each null child so the original shape is preserved.
What is the time and space complexity of this solution?
Time O(n), space O(n) for output plus O(h) call-stack space.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.