AlgoTales · Roadmap

Inorder

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

Where you will meet this in real life

Inorder traversal visits a tree by finishing everything on the left first, then the node itself, then everything on the right. On a search tree that gives you the values in sorted order without any separate sorting step, which is why it keeps coming back in real apps.

Practical use cases

  • Web app: Sorted product list straight from the tree. A shop keeps product prices in a search tree so new items can be added quickly. When the admin opens the "all products by price" report, the code walks the tree inorder and gets cheapest to costliest already in order. There is no extra sort call, and the report opens instantly even with 50,000 products.
  • Web app: Exporting a sorted CSV of customers. A school portal stores student roll numbers in an ordered structure. When the teacher clicks "Download attendance sheet", an inorder walk writes rows in roll-number order, top to bottom. Nobody has to re-sort the file in Excel afterwards, and the sheet is always in the order the teacher expects.
  • System: Printing expressions and checking an index. Compilers turn a formula like 3 + 4 * 2 into a tree, and an inorder walk prints it back in the familiar left-operator-right form. Database tools also walk an ordered index inorder to confirm that its entries really are in sorted sequence.

The story: The Library Shelf that Reads Itself

Grandpa Bhaskar had a funny old bookshelf built like a tree: a middle shelf, with a smaller shelf hanging to its left and another to its right, and the same pattern repeating beneath. "My books are arranged by a rule," he told Mira. "Everything on the left comes before the book on this shelf, and everything on the right comes after."

Mira wanted to read the books in their proper order. Starting at the top shelf and reading the middle book first would be a mistake. Grandpa taught her the right habit: "At each shelf, go left first and finish all of that, then read this shelf's book, then go right." She walked down the left shelves to the very end before reading even one book.

The first book she read was from the farthest left shelf. After that, she climbed back one shelf and read its book, then explored that shelf's right side. By the time she reached the far right shelf, she had read every book exactly once, in perfect order.

This is inorder traversal: Left, Root, Right. On a tree that keeps smaller things on the left and bigger on the right (a binary search tree, coming soon), inorder reads everything in sorted order, like a magic bookshelf.

How to spot this problem, and where you need it

You hold data in a tree and need to list it in sorted order, or you want the first few smallest values, without copying everything into an array and sorting it again.

Signs you need it

  • The data lives in a binary search tree or an ordered map, and the screen needs "A to Z" or "low to high" output.
  • The problem statement says "return the sorted values", "k-th smallest", or "check whether this tree is a valid search tree".
  • Your code pulls everything out of a structure and calls sort() each time the page loads, even though the data was already kept in order.

Where to use it in a project

  • Report pages and CSV exports that must list records in key order from an ordered structure.
  • Unit tests that confirm an ordered index or map still returns keys in ascending order after many inserts and deletes.

The solution

Write a function that does three things in this exact order: go into the left child, then handle the current node (print it or add it to a result list), then go into the right child. Stop when a child is empty. Because a search tree keeps smaller values on the left and bigger on the right, the handling order comes out sorted by itself.

Payoff: Before: pull 50,000 items out and sort them on every request. After: one walk over the tree gives them already sorted, and you can stop early after the first 10.

Explain it like I am 8

Stand at a node and think: "first everything to my left, then me, then everything to my right". You always dive left until you cannot go further, and only then speak. It reads the tree from its left edge to its right edge, like reading a line of text.

How it works, step by step

  1. At a node, first recursively handle the whole left subtree.
  2. Then visit the node itself (print it, store it).
  3. Then recursively handle the whole right subtree.
  4. An empty spot means "return right away".
  5. On a binary search tree the output comes out sorted. On ordinary trees it simply reads the tree left to right.

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;
}

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

$out = [];
inorder(sampleTree(), $out);
echo implode(' ', $out) . PHP_EOL;    // 4 2 7 5 1 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;
}

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

const out = [];
inorder(sampleTree(), out);
console.log(out.join(' '));         // 4 2 7 5 1 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;
    }

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

    public static void main(String[] args) {
        List<Integer> out = new ArrayList<>();
        inorder(sampleTree(), out);
        System.out.println(out.stream().map(String::valueOf).collect(Collectors.joining(" ")));   // 4 2 7 5 1 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
}

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

// 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{}
	inorder(sampleTree(), &out)
	fmt.Println(joinInts(out, " ")) // 4 2 7 5 1 3 6
}

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

Watch out for

  • Saying the node on the way down instead of after the left side is done. That turns inorder into preorder.
  • Expecting sorted output from any tree. Sorted order only appears when the tree is a binary search tree.
  • Forgetting that nodes with no left child say themselves immediately, which makes the order look "jumpy" at first.

Quick check

  1. What is the inorder traversal of our example tree?
    • 4 2 7 5 1 3 6
    • 4 7 5 2 6 3 1
    • 1 2 4 5 7 3 6
  2. Inorder on a binary search tree gives...
    • Values in reverse of insertion
    • Only the leaves
    • Values in sorted order
  3. When is a node visited in inorder?
    • Before its children
    • After its left subtree, before its right subtree
    • After both of its subtrees