Trees & BST · Pattern 10 of 12
Build a tree from traversals, and serialize it
Preorder tells you the root first; inorder tells you which values are left of it. Serializing is the same idea in reverse: write a traversal with markers for null, then read it back in the same order.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Rebuild a tree from two traversal arrays
- Rebuild a BST from one traversal
- Turn a tree into a string and back
The template
// preorder gives the root, inorder splits the rest into left and right
int pre;
Map<Integer, Integer> pos = new HashMap<>(); // value -> index in inorder
TreeNode buildTree(int[] preorder, int[] inorder) {
pre = 0;
for (int i = 0; i < inorder.length; i++) pos.put(inorder[i], i);
return build(preorder, 0, inorder.length - 1);
}
TreeNode build(int[] preorder, int lo, int hi) { // inorder[lo..hi] is this subtree
if (lo > hi) return null;
TreeNode root = new TreeNode(preorder[pre++]);
int mid = pos.get(root.val);
root.left = build(preorder, lo, mid - 1); // left first, like preorder
root.right = build(preorder, mid + 1, hi);
return root;
}
// serialize as preorder with "#" for null; deserialize reads it back in the same order
String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
write(root, sb);
return sb.substring(1); // drop the first comma
}
void write(TreeNode node, StringBuilder sb) {
if (node == null) { sb.append(",#"); return; }
sb.append(',').append(node.val);
write(node.left, sb);
write(node.right, sb);
}
TreeNode deserialize(String data) {
return read(new ArrayDeque<>(Arrays.asList(data.split(","))));
}
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;
} # preorder gives the root, inorder splits the rest into left and right
def build_tree(preorder, inorder):
pos = {v: i for i, v in enumerate(inorder)} # value -> index in inorder
it = iter(preorder)
def build(lo, hi): # inorder[lo..hi] is this subtree
if lo > hi:
return None
root = TreeNode(next(it))
mid = pos[root.val]
root.left = build(lo, mid - 1) # left first, like preorder
root.right = build(mid + 1, hi)
return root
return build(0, len(inorder) - 1)
# serialize as preorder with "#" for null; deserialize reads it back in the same order
def serialize(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(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() // preorder gives the root, inorder splits the rest into left and right
TreeNode* build(vector<int>& preorder, int& pre, int lo, int hi, unordered_map<int, int>& pos) {
if (lo > hi) return nullptr; // inorder[lo..hi] is this subtree
TreeNode* root = new TreeNode(preorder[pre++]);
int mid = pos[root->val];
root->left = build(preorder, pre, lo, mid - 1, pos); // left first, like preorder
root->right = build(preorder, pre, mid + 1, hi, pos);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
unordered_map<int, int> pos; // value -> index in inorder
for (int i = 0; i < (int)inorder.size(); i++) pos[inorder[i]] = i;
int pre = 0;
return build(preorder, pre, 0, (int)inorder.size() - 1, pos);
}
// serialize as preorder with "#" for null; deserialize reads it back in the same order
void write(TreeNode* node, string& out) {
if (!node) { out += ",#"; return; }
out += "," + to_string(node->val);
write(node->left, out);
write(node->right, out);
}
string serialize(TreeNode* root) {
string out;
write(root, out);
return out.substr(1); // drop the first comma
}
TreeNode* readNode(istringstream& in) {
string t;
getline(in, t, ',');
if (t == "#") return nullptr;
TreeNode* node = new TreeNode(stoi(t));
node->left = readNode(in);
node->right = readNode(in);
return node;
}
TreeNode* deserialize(string data) {
istringstream in(data);
return readNode(in);
} // preorder gives the root, inorder splits the rest into left and right
function buildTree(preorder, inorder) {
const pos = new Map(inorder.map((v, i) => [v, i])); // value -> index in inorder
let pre = 0;
function build(lo, hi) { // inorder[lo..hi] is this subtree
if (lo > hi) return null;
const root = new TreeNode(preorder[pre++]);
const mid = pos.get(root.val);
root.left = build(lo, mid - 1); // left first, like preorder
root.right = build(mid + 1, hi);
return root;
}
return build(0, inorder.length - 1);
}
// serialize as preorder with "#" for null; deserialize reads it back in the same order
function serialize(root) {
const out = [];
(function write(node) {
if (!node) { out.push('#'); return; }
out.push(node.val);
write(node.left);
write(node.right);
})(root);
return out.join(',');
}
function deserialize(data) {
const tokens = data.split(',');
let i = 0;
function read() {
const t = tokens[i++];
if (t === '#') return null;
const node = new TreeNode(Number(t));
node.left = read();
node.right = read();
return node;
}
return read();
} The variations
-
1Rebuild from two traversals
Take the next root from preorder (or the last from postorder), find it in inorder with a map, and recurse on the two sides. The traversal order decides which side you build first.
Worked example Construct Binary Tree from Preorder and Inorder Traversal Medium ▶ Watch the walkthroughNow you solve -
2A BST from one traversal
The BST order replaces inorder. Pass an upper bound down: take the next preorder value while it is below the bound, the left child gets the node's value as its bound. O(n).
-
3Serialize with null markers
Write preorder with
#for every missing child, then read it back with one shared index. For an N-ary tree, write each node's child count after its value instead.Now you solve
Mistakes to avoid
- Searching inorder for the root on every call: O(n²). Build a value-to-index map once.
- Inorder + postorder: postorder gives roots from the end, so build the right subtree before the left one.
- Serializing without null markers: preorder alone cannot tell where a subtree ends (it can only for a BST, thanks to the order).
Mark it done once you can write the template from memory and you have solved the worked examples yourself.