AlgoTales · Roadmap

Serialize/deserialize

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Serializing turns a tree into a flat piece of text or a list that can be saved or sent, and deserializing rebuilds the exact same tree from it. Anything you store in a database, cache or API response goes through this step.

Practical use cases

  • Web app: Saving a menu tree to the database. An admin edits a multi-level navigation menu using drag and drop, and clicks Save. The tree must be flattened into text or rows, so that loading the page later rebuilds the same menu. The flat form records each item and where branches end, so nothing is lost or moved.
  • Web app: Sending a folder structure through an API. A cloud-storage app sends the user's folder tree to the phone app as one JSON response. The server serializes the tree and the phone rebuilds it. Both sides agree on the order, so 5,000 folders arrive in one request and appear exactly as on the website.
  • System: Caches, files and network messages. Redis values, session files and messages between services are all plain text or bytes, so any tree has to be flattened first. Tools that save a document outline or a game level to disk use the same save-and-rebuild pair. If the two halves disagree even slightly, the loaded data looks corrupted, so the order must be fixed and documented.

The story: The Family Tree on a Postcard

Grandpa Bhaskar lived far away, and he wanted to send Mira the family tree. But the post office only took a single line of text on a postcard. "How do I squeeze a whole tree into one line, and how will Mira draw it back?" he wondered.

He decided to write names in a fixed order: a person, then everything under their left child, then everything under their right child. But there was a problem: if someone has only one child, the reader could not tell which side. So he wrote a small # wherever a child was missing.

A postcard read "3, 1, #, #, 6, 4, #, #, 7, #, #". Mira read it from the left: 3 is the top. Next is 1, so that is its left child; then # # means 1 has no children. The next number, 6, is 3's right child, and so on. Every # told her "stop, go back up". The whole tree appeared out of a line of text. Turning a tree into text is serialization; rebuilding it is deserialization.

How to spot this problem, and where you need it

You have a tree in memory and need to store it, cache it or send it somewhere, then get exactly the same tree back later.

Signs you need it

  • You must put a tree-shaped thing into a single text column, a file, a Redis key or an API response.
  • The statement says "encode and decode", "save and restore", "convert to string and back".
  • Your saved data loses the shape: after reloading, children end up under the wrong parent or in the wrong order.

Where to use it in a project

  • Saving drag-and-drop menus, category trees and page builders to a database or file.
  • Caching a computed tree in Redis and sending it between a backend and a mobile or browser client.

The solution

Choose a fixed visiting order, such as preorder, and write each value in that order. For every empty child, write a marker like "null" so the shape is recorded. To rebuild, read the values in the same order: take one, make a node, rebuild its left child, then its right child, treating each marker as "no child here".

Payoff: Before: saved menus that reloaded with branches in the wrong place. After: a round trip that returns an identical tree every time.

Explain it like I am 8

Imagine telling a friend over the phone how to build a Lego tower with branches. You say each brick and, when a branch ends, you say "nothing here". Your friend follows the same order and builds the same thing.

How it works, step by step

  1. Serialize with preorder: write the node, then its left side, then its right side.
  2. When a child is missing, write a marker such as # (this is what keeps the shape unique).
  3. Join the pieces into one string, e.g. with commas.
  4. Deserialize by reading the pieces in the same order: a number makes a node and then builds its left subtree, then its right subtree. A # returns "no node".

The code in four languages

PHP

<?php
class Node {
    public ?Node $left = null;
    public ?Node $right = null;
    public function __construct(public int $val) {}
}

function serialize_tree(?Node $n): string {
    if ($n === null) return '#';                         // marker for "no child"
    return $n->val . ',' . serialize_tree($n->left) . ',' . serialize_tree($n->right);
}

function deserialize_tree(string $s): ?Node {
    $tokens = explode(',', $s);
    $i = 0;                                              // where we are in the message
    $build = function () use (&$build, &$tokens, &$i): ?Node {
        $t = $tokens[$i++];
        if ($t === '#') return null;                     // empty spot
        $node = new Node((int)$t);
        $node->left = $build();                          // left subtree comes first
        $node->right = $build();                         // then the right subtree
        return $node;
    };
    return $build();
}

// build  3 -> (1, 6 -> (4, 7))
$root = new Node(3);
$root->left = new Node(1);
$root->right = new Node(6);
$root->right->left = new Node(4);
$root->right->right = new Node(7);

$text = serialize_tree($root);
echo $text, PHP_EOL;                                     // 3,1,#,#,6,4,#,#,7,#,#
$copy = deserialize_tree($text);
echo serialize_tree($copy) === $text ? 'same tree' : 'different', PHP_EOL;

JavaScript

class Node {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}

function serialize(n) {
  if (n === null) return '#';                            // marker for "no child"
  return n.val + ',' + serialize(n.left) + ',' + serialize(n.right);
}

function deserialize(s) {
  const tokens = s.split(',');
  let i = 0;                                             // where we are in the message
  function build() {
    const t = tokens[i++];
    if (t === '#') return null;                          // empty spot
    const node = new Node(Number(t));
    node.left = build();                                 // left subtree comes first
    node.right = build();                                // then the right subtree
    return node;
  }
  return build();
}

// build  3 -> (1, 6 -> (4, 7))
const root = new Node(3);
root.left = new Node(1);
root.right = new Node(6);
root.right.left = new Node(4);
root.right.right = new Node(7);

const text = serialize(root);
console.log(text);                                       // 3,1,#,#,6,4,#,#,7,#,#
const copy = deserialize(text);
console.log(serialize(copy) === text ? 'same tree' : 'different');

Java

import java.util.*;

public class Main {
    static class Node {
        int val;
        Node left, right;
        Node(int val) { this.val = val; }
    }

    static String serialize(Node n) {
        if (n == null) return "#";                          // marker for "no child"
        return n.val + "," + serialize(n.left) + "," + serialize(n.right);
    }

    static Node deserialize(String s) {
        String[] tokens = s.split(",");
        return build(tokens, new int[]{0});
    }

    // pos[0] is where we are in the message
    static Node build(String[] tokens, int[] pos) {
        String t = tokens[pos[0]++];
        if (t.equals("#")) return null;                     // empty spot
        Node node = new Node(Integer.parseInt(t));
        node.left = build(tokens, pos);                     // left subtree comes first
        node.right = build(tokens, pos);                    // then the right subtree
        return node;
    }

    public static void main(String[] args) {
        // build  3 -> (1, 6 -> (4, 7))
        Node root = new Node(3);
        root.left = new Node(1);
        root.right = new Node(6);
        root.right.left = new Node(4);
        root.right.right = new Node(7);

        String text = serialize(root);
        System.out.println(text);                           // 3,1,#,#,6,4,#,#,7,#,#
        Node copy = deserialize(text);
        System.out.println(serialize(copy).equals(text) ? "same tree" : "different");
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

type Node struct {
	val         int
	left, right *Node
}

func serialize(n *Node) string {
	if n == nil {
		return "#" // marker for "no child"
	}
	return strconv.Itoa(n.val) + "," + serialize(n.left) + "," + serialize(n.right)
}

func deserialize(s string) *Node {
	tokens := strings.Split(s, ",")
	i := 0 // where we are in the message
	var build func() *Node
	build = func() *Node {
		t := tokens[i]
		i++
		if t == "#" {
			return nil // empty spot
		}
		v, _ := strconv.Atoi(t)
		node := &Node{val: v}
		node.left = build()  // left subtree comes first
		node.right = build() // then the right subtree
		return node
	}
	return build()
}

func main() {
	// build  3 -> (1, 6 -> (4, 7))
	root := &Node{val: 3}
	root.left = &Node{val: 1}
	root.right = &Node{val: 6}
	root.right.left = &Node{val: 4}
	root.right.right = &Node{val: 7}

	text := serialize(root)
	fmt.Println(text) // 3,1,#,#,6,4,#,#,7,#,#
	copyTree := deserialize(text)
	if serialize(copyTree) == text {
		fmt.Println("same tree")
	} else {
		fmt.Println("different")
	}
}

Time: O(n) · Extra space: O(n). Both directions touch each node once; the text holds one piece per node plus one per empty spot.

Watch out for

  • Leaving out the # markers. Without them, many different trees produce the same list of numbers.
  • Using a separator that can appear in the data. Pick one that cannot (a comma is fine for numbers).
  • Reading the pieces in a different order from the one used to write them. Both sides must agree: root, left, right.

Quick check

  1. Why do we write # for empty children?
    • To make the text shorter
    • So the exact shape can be rebuilt
    • To sort the values
  2. Which traversal order did we use?
    • Inorder
    • Preorder (root, left, right)
    • Postorder
  3. How many pieces does a tree with 5 nodes produce (including #s)?
    • 5
    • 11
    • 10