AlgoTales · Roadmap

Preorder

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Preorder visits a node first, then everything in its left part, then everything in its right part. Because each parent appears before its children, it is the natural order for copying a tree or saving it to a file.

Practical use cases

  • Web app: Printing a folder tree with indentation. A documentation site shows its menu as an indented list. The code prints each folder name first and then its children, going down level by level, and adds a few spaces per level. The result looks exactly like the structure the author planned.
  • Web app: Exporting categories to JSON. An admin tool exports a category tree so it can be imported on another shop. Writing each parent before its children means the import can recreate parents first, so every child always finds its parent waiting.
  • System: Copying a tree and prefix expressions. To make an exact copy of a tree, you create a node, then copy its left and right parts, which is preorder. Calculators also write expressions in prefix form using the same visiting order. Because parents come before children, the saved order can be replayed to rebuild a perfect copy.

The story: The Roll-Call at Mrs. Sharma's School

Every morning, Mrs. Sharma took attendance for the whole school the same way. She would start with the principal, write the name on the register, then ask the principal's two assistants to do the same for their own teams. Each assistant wrote their name first, then asked their team members to do the same.

One day a new teacher asked, "Why do you write the boss's name first, before the team?" Mrs. Sharma said, "Because if the register is ever lost, I can rebuild the whole school chart from it. The first name is always the top, followed by the left team, then the right team."

This was a clever point. When names are written boss first, then left team, then right team, the order itself remembers the shape of the tree. If you want to copy the school's chart onto a new page, you create the boss first, then the teams below.

Kabir called it "Root, Left, Right". Mira called it "say it as soon as you arrive". Both are right: that is preorder traversal, the first of the three famous depth-first tree walks.

How to spot this problem, and where you need it

You need to process each parent before its children, such as when saving, copying or printing a tree, so that the structure can be rebuilt in the same order.

Signs you need it

  • Import or restore code fails because a child row is created before its parent exists.
  • The problem says "preorder", "serialize a tree", "copy a tree" or "print with indentation".
  • You want the output to read top-down like a table of contents, with parents above their children.

Where to use it in a project

  • Exporting and importing nested data such as categories, menus and permission trees.
  • Rendering indented lists for folders, outlines and navigation menus.

The solution

Write a function that handles a node in three steps: first do the work for the node itself, such as printing or saving it; then call the same function on the left child; then on the right child. If the node is missing, return at once. Because the node comes before its children, the saved sequence lists every parent before its descendants, and replaying it rebuilds the tree.

Payoff: Before: imports failed because children were created before parents. After: parents always come first, and the whole category tree restores cleanly.

Explain it like I am 8

Walk around a family chart. Whenever you arrive at a person, shout their name straight away. Then visit everyone in their left family, then everyone in their right family. "Hello first, then the kids!" is preorder.

How it works, step by step

  1. Arrive at a node and visit it right now (print it, copy it, count it).
  2. Then recursively do the same for the entire left subtree.
  3. Then recursively do the same for the entire right subtree.
  4. An empty spot (null) means "do nothing and go back".
  5. The node is always listed before anything below it, so the first value is always the root.

The code in four languages

PHP

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

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree(): TreeNode {
    $root = new TreeNode(1);
    $root->left = new TreeNode(2);
    $root->right = new TreeNode(3);
    $root->left->left = new TreeNode(4);
    $root->left->right = new TreeNode(5);
    $root->right->right = new TreeNode(6);
    $root->left->right->left = new TreeNode(7);
    return $root;
}

// Preorder: Root, Left, Right
function preorder(?TreeNode $n, array &$out): void {
    if ($n === null) return;          // empty spot: nothing to do
    $out[] = $n->val;                 // 1. visit the node FIRST
    preorder($n->left, $out);         // 2. whole left side
    preorder($n->right, $out);        // 3. whole right side
}

// Saving the tree as text: '#' marks an empty spot, so the shape is remembered.
function serializeTree(?TreeNode $n): string {
    if ($n === null) return '#';
    return $n->val . ' ' . serializeTree($n->left) . ' ' . serializeTree($n->right);
}

$out = [];
preorder(sampleTree(), $out);
echo implode(' ', $out) . PHP_EOL;        // 1 2 4 5 7 3 6
echo serializeTree(sampleTree()) . PHP_EOL;   // 1 2 4 # # 5 7 # # # 3 # 6 # #

JavaScript

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

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree() {
  const root = new TreeNode(1);
  root.left = new TreeNode(2);
  root.right = new TreeNode(3);
  root.left.left = new TreeNode(4);
  root.left.right = new TreeNode(5);
  root.right.right = new TreeNode(6);
  root.left.right.left = new TreeNode(7);
  return root;
}

// Preorder: Root, Left, Right
function preorder(n, out) {
  if (n === null) return;           // empty spot: nothing to do
  out.push(n.val);                  // 1. visit the node FIRST
  preorder(n.left, out);            // 2. whole left side
  preorder(n.right, out);           // 3. whole right side
}

// Saving the tree as text: '#' marks an empty spot, so the shape is remembered.
function serializeTree(n) {
  if (n === null) return '#';
  return n.val + ' ' + serializeTree(n.left) + ' ' + serializeTree(n.right);
}

const out = [];
preorder(sampleTree(), out);
console.log(out.join(' '));               // 1 2 4 5 7 3 6
console.log(serializeTree(sampleTree()));     // 1 2 4 # # 5 7 # # # 3 # 6 # #

Java

import java.util.*;
import java.util.stream.*;

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

    // The example tree:      1
    //                       /   \
    //                      2     3
    //                     / \     \
    //                    4   5     6
    //                       /
    //                      7
    static TreeNode sampleTree() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(6);
        root.left.right.left = new TreeNode(7);
        return root;
    }

    // Preorder: Root, Left, Right
    static void preorder(TreeNode n, List<Integer> out) {
        if (n == null) return;            // empty spot: nothing to do
        out.add(n.val);                   // 1. visit the node FIRST
        preorder(n.left, out);            // 2. whole left side
        preorder(n.right, out);           // 3. whole right side
    }

    // Saving the tree as text: '#' marks an empty spot, so the shape is remembered.
    static String serializeTree(TreeNode n) {
        if (n == null) return "#";
        return n.val + " " + serializeTree(n.left) + " " + serializeTree(n.right);
    }

    public static void main(String[] args) {
        List<Integer> out = new ArrayList<>();
        preorder(sampleTree(), out);
        System.out.println(out.stream().map(String::valueOf).collect(Collectors.joining(" ")));   // 1 2 4 5 7 3 6
        System.out.println(serializeTree(sampleTree()));   // 1 2 4 # # 5 7 # # # 3 # 6 # #
    }
}

Go

package main

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

type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// The example tree:      1
//
//	   /   \
//	  2     3
//	 / \     \
//	4   5     6
//	   /
//	  7
func sampleTree() *TreeNode {
	root := &TreeNode{Val: 1}
	root.Left = &TreeNode{Val: 2}
	root.Right = &TreeNode{Val: 3}
	root.Left.Left = &TreeNode{Val: 4}
	root.Left.Right = &TreeNode{Val: 5}
	root.Right.Right = &TreeNode{Val: 6}
	root.Left.Right.Left = &TreeNode{Val: 7}
	return root
}

// Preorder: Root, Left, Right
func preorder(n *TreeNode, out *[]int) {
	if n == nil {
		return // empty spot: nothing to do
	}
	*out = append(*out, n.Val) // 1. visit the node FIRST
	preorder(n.Left, out)      // 2. whole left side
	preorder(n.Right, out)     // 3. whole right side
}

// serializeTree saves the tree as text: '#' marks an empty spot, so the shape is remembered.
func serializeTree(n *TreeNode) string {
	if n == nil {
		return "#"
	}
	return strconv.Itoa(n.Val) + " " + serializeTree(n.Left) + " " + serializeTree(n.Right)
}

// joinInts glues the numbers together with a separator.
func joinInts(xs []int, sep string) string {
	parts := make([]string, len(xs))
	for i, v := range xs {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, sep)
}

func main() {
	out := []int{}
	preorder(sampleTree(), &out)
	fmt.Println(joinInts(out, " "))          // 1 2 4 5 7 3 6
	fmt.Println(serializeTree(sampleTree())) // 1 2 4 # # 5 7 # # # 3 # 6 # #
}

Time: O(n) · Extra space: O(h). Each node is visited once. The recursion stack goes as deep as the tree is tall (h).

Watch out for

  • Mixing up the order words. In preorder, the root comes before its children; in postorder after; in inorder in the middle.
  • Forgetting the null check, so the code tries to read .val of nothing.
  • Expecting preorder alone to rebuild a tree. Without null markers (or a second traversal), several different trees can give the same list.

Quick check

  1. What is the preorder of our example tree?
    • 1 2 4 5 7 3 6
    • 4 7 5 2 6 3 1
    • 1 2 3 4 5 6 7
    • 4 2 7 5 1 3 6
  2. In preorder, the very first value is always...
    • The smallest value
    • The root
    • The left-most leaf
  3. Which task is the most natural fit for preorder?
    • Copying a tree
    • Deleting a tree safely
    • Printing numbers in sorted order