Build and serialize trees
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Rebuilding and serializing trees converts between flat memory strings and linked node structures.
Rebuilding a tree from preorder and inorder
A single traversal cannot uniquely reconstruct a general binary tree. Preorder visits root before children. Inorder places left descendants before root and right descendants after. Combining both traversals identifies the root and partitions left and right subtrees.
Example 1 · Rebuild Tree from Preorder and Inorder
import java.util.HashMap;import java.util.Map;
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static int preIndex = 0; static Map<Integer, Integer> inMap = new HashMap<>();
static TreeNode build(int[] preorder, int inStart, int inEnd) { if (inStart > inEnd) return null; int rootVal = preorder[preIndex++]; TreeNode root = new TreeNode(rootVal); int inIndex = inMap.get(rootVal);
root.left = build(preorder, inStart, inIndex - 1); root.right = build(preorder, inIndex + 1, inEnd); return root; }
static void printInorder(TreeNode node) { if (node == null) return; printInorder(node.left); System.out.print(node.val + " "); printInorder(node.right); }
public static void main(String[] args) { int[] preorder = {3, 9, 20, 15, 7}; int[] inorder = {9, 3, 15, 20, 7};
for (int i = 0; i < inorder.length; i++) { inMap.put(inorder[i], i); }
TreeNode root = build(preorder, 0, inorder.length - 1); printInorder(root); System.out.println(); }}9 3 15 20 7
What this code does
- Preorder pointer sequentially selects the root value for each subtree.
- Inorder map locates the split boundary between left and right subtrees.
- Recursive calls construct left and right child pointers with updated index bounds.
A naive search scans the inorder array linearly for each root. That takes quadratic time on skewed trees. A hash map maps each node value to its inorder index in constant lookup time. Trace preorder [3, 9, 20, 15, 7] and inorder [9, 3, 15, 20, 7]. The first preorder element is 3. In inorder, 3 sits at index 1. Elements to the left form the left subtree [9]. Elements to the right form the right subtree [15, 20, 7]. Recursively repeat this slicing until all subtrees are constructed.
Serialize and deserialize with delimiter tokens
Serialization converts a linked memory structure into a flat string or byte sequence. Deserialization reads the formatted string and recreates the pointer references in memory.
Example 2 · Preorder String Serialization
import java.util.Arrays;import java.util.LinkedList;import java.util.Queue;
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static void serializeHelper(TreeNode root, StringBuilder sb) { if (root == null) { sb.append("#,"); return; } sb.append(root.val).append(","); serializeHelper(root.left, sb); serializeHelper(root.right, sb); }
static String serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); serializeHelper(root, sb); return sb.toString(); }
static TreeNode deserializeHelper(Queue<String> queue) { String val = queue.poll(); if (val.equals("#")) return null; TreeNode node = new TreeNode(Integer.parseInt(val)); node.left = deserializeHelper(queue); node.right = deserializeHelper(queue); return node; }
static TreeNode deserialize(String data) { Queue<String> queue = new LinkedList<>(Arrays.asList(data.split(","))); return deserializeHelper(queue); }
public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3);
String serialized = serialize(root); System.out.println("Serialized: " + serialized);
TreeNode rebuilt = deserialize(serialized); System.out.println("Rebuilt root: " + rebuilt.val); System.out.println("Rebuilt left: " + rebuilt.left.val); System.out.println("Rebuilt right: " + rebuilt.right.val); }}Serialized: 1,2,#,#,3,#,#, Rebuilt root: 1 Rebuilt left: 2 Rebuilt right: 3
What this code does
- Nodes are recorded in preorder format with a hash symbol for null children.
- Deserialization populates a queue with tokens split by commas.
- Each recursive step takes the next token and constructs the tree hierarchy.
Preorder traversal with null indicators uniquely encodes any binary tree shape. Append node values separated by commas. Append null markers for absent child pointers. To deserialize, split the string into tokens and load them into a FIFO queue. A recursive function polls the next token from the queue. If the token is null, return null. Otherwise create a node and recursively attach its left and right children.
Real-world storage: files, JSON and databases
Compilers serialize abstract syntax trees into binary files for incremental compilation caches. Web browsers parse HTML strings into DOM trees and serialize them back during exports.
Example 3 · JSON Formatted Nested Tree
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static String toJson(TreeNode root) { if (root == null) return "null"; StringBuilder sb = new StringBuilder(); sb.append("{\"val\":").append(root.val); sb.append(",\"left\":").append(toJson(root.left)); sb.append(",\"right\":").append(toJson(root.right)); sb.append("}"); return sb.toString(); }
public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2);
System.out.println(toJson(root)); }}{"val":1,"left":{"val":2,"left":null,"right":null},"right":null}What this code does
- Every node converts into a JSON object containing value and child references.
- Null pointers format directly into JSON null literals.
- Nested objects preserve the complete hierarchical structure for network transmission.
Databases store tree relationships using parent foreign keys or nested set models. Network APIs transmit hierarchical category trees as structured JSON payloads. Compact serialization formats reduce network payload sizes and decrease disk usage during storage.
Next step
Check your understanding
10 quick questions