AlgoTales · Roadmap

Zigzag traversal

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

Where you will meet this in real life

Zigzag traversal reads a tree level by level but flips direction on each level: left to right, then right to left, and so on. It shows how a small tweak to level-order gives a different, snake-like reading order.

Practical use cases

  • Web app: Snakes-and-ladders style game board. A browser board game numbers squares row by row, but every second row runs backwards, like Snakes and Ladders. Producing the numbering with a zigzag walk gives each row in the proper direction. The same code prints board sizes from 6 by 6 up to 10 by 10.
  • Web app: Alternating-direction report layout. A printable exam-hall sheet lists seats in a snake pattern, row 1 left to right, row 2 right to left, and so on. The page generates the print order by reversing every second row. The invigilator follows the sheet down the hall without wandering back to the start of each row.
  • System: Scan paths and embroidery machines. Machines that scan a surface or stitch a pattern move in a snake path so they never waste time returning to the start. Zigzag order is the same idea applied to tree levels.

The story: The Snakes and Ladders Board

Kabir and Mira unfolded their old Snakes and Ladders board. Mira noticed something odd: the bottom row went 1, 2, 3 ... 10 from left to right. But the row above it went 20, 19, 18 ... 11, right to left! "Why does it zigzag?"

Kabir laughed. "Because your token walks like a snake: it finishes a row and just steps up to the square above it, then comes back the other way. No jumping to the far end."

Mira thought about her tree drawing. A normal level-by-level reading always goes left to right, then jumps back to the left for the next level. What if she read it like the board: level one left to right, level two right to left, level three left to right again? She kept her usual queue-based level walk and simply reversed every second level. That is the zigzag traversal (also called spiral order).

How to spot this problem, and where you need it

You need to output layered data in a snake pattern, where every other row is reversed, instead of always reading each row left to right.

Signs you need it

  • The problem says "zigzag", "spiral-like", "alternate direction each level" or "boustrophedon".
  • A numbering or print order must keep adjacent rows connected end to end, as on a game board.
  • You already walk the tree level by level and just need to flip every second level.

Where to use it in a project

  • Board-game number grids and puzzle layouts that alternate direction on each row.
  • Print or scan orders for exam halls, warehouse picking routes and similar row-based walks.

The solution

Do a normal level-order walk with a queue, gathering each level into its own list. Keep a flag that starts as left to right. After finishing a level, if the flag says right to left, reverse that level's list. Then flip the flag. Append the list to the result and repeat for the next level.

Payoff: Before: manual if-else numbering that breaks when the board size changes. After: one short loop that handles any size, 6 rows or 60.

Explain it like I am 8

Walk through a school corridor with classrooms on each floor. On floor 1 you go left to right, take the stairs, then on floor 2 you walk back right to left. You never run back to the start of the corridor. That is zigzag.

How it works, step by step

  1. Do a normal level order walk with a queue: process all nodes of one level together.
  2. Keep a flag leftToRight, starting as true.
  3. After collecting a level's values, reverse that list if the flag is false.
  4. Flip the flag and move to the next level. Collect each level as its own list.

The code in four languages

PHP

<?php
class Node {
    public ?Node $left = null;
    public ?Node $right = null;
    public function __construct(public int $val) {}
}
function insert(?Node $n, int $v): Node {
    if ($n === null) return new Node($v);
    if ($v < $n->val) $n->left = insert($n->left, $v);
    else $n->right = insert($n->right, $v);
    return $n;
}

function zigzag(?Node $root): array {
    if ($root === null) return [];
    $result = [];
    $queue = [$root];
    $leftToRight = true;
    while ($queue) {
        $level = [];
        $next = [];
        foreach ($queue as $node) {          // one whole level
            $level[] = $node->val;
            if ($node->left)  $next[] = $node->left;
            if ($node->right) $next[] = $node->right;
        }
        $result[] = $leftToRight ? $level : array_reverse($level);
        $leftToRight = !$leftToRight;        // flip direction for the next level
        $queue = $next;
    }
    return $result;
}

$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
foreach (zigzag($root) as $row) echo '[', implode(',', $row), '] ';
echo PHP_EOL;   // [8] [10,3] [1,6,14] [13,7,4]

JavaScript

class Node {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}
function insert(n, v) {
  if (n === null) return new Node(v);
  if (v < n.val) n.left = insert(n.left, v);
  else n.right = insert(n.right, v);
  return n;
}

function zigzag(root) {
  if (root === null) return [];
  const result = [];
  let queue = [root];
  let leftToRight = true;
  while (queue.length) {
    const level = [];
    const next = [];
    for (const node of queue) {             // one whole level
      level.push(node.val);
      if (node.left) next.push(node.left);
      if (node.right) next.push(node.right);
    }
    result.push(leftToRight ? level : level.reverse());
    leftToRight = !leftToRight;             // flip direction for the next level
    queue = next;
  }
  return result;
}

let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
console.log(zigzag(root).map(r => '[' + r.join(',') + ']').join(' '));   // [8] [10,3] [1,6,14] [13,7,4]

Java

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

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

    static Node insert(Node n, int v) {
        if (n == null) return new Node(v);
        if (v < n.val) n.left = insert(n.left, v);
        else n.right = insert(n.right, v);
        return n;
    }

    static Node buildDemo() {
        Node root = null;
        for (int v : new int[]{8, 3, 10, 1, 6, 14, 4, 7, 13}) root = insert(root, v);
        return root;
    }

    static List<List<Integer>> zigzag(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        List<Node> queue = List.of(root);
        boolean leftToRight = true;
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            List<Node> next = new ArrayList<>();
            for (Node node : queue) {                 // one whole level
                level.add(node.val);
                if (node.left != null) next.add(node.left);
                if (node.right != null) next.add(node.right);
            }
            if (!leftToRight) Collections.reverse(level);
            result.add(level);
            leftToRight = !leftToRight;               // flip direction for the next level
            queue = next;
        }
        return result;
    }

    public static void main(String[] args) {
        String text = zigzag(buildDemo()).stream()
                .map(r -> r.stream().map(String::valueOf).collect(Collectors.joining(",", "[", "]")))
                .collect(Collectors.joining(" "));
        System.out.println(text);   // [8] [10,3] [1,6,14] [13,7,4]
    }
}

Go

package main

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

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

func insert(n *Node, v int) *Node {
	if n == nil {
		return &Node{val: v}
	}
	if v < n.val {
		n.left = insert(n.left, v)
	} else {
		n.right = insert(n.right, v)
	}
	return n
}

func buildDemo() *Node {
	var root *Node
	for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
		root = insert(root, v)
	}
	return root
}

func zigzag(root *Node) [][]int {
	result := [][]int{}
	if root == nil {
		return result
	}
	queue := []*Node{root}
	leftToRight := true
	for len(queue) > 0 {
		level := []int{}
		next := []*Node{}
		for _, node := range queue { // one whole level
			level = append(level, node.val)
			if node.left != nil {
				next = append(next, node.left)
			}
			if node.right != nil {
				next = append(next, node.right)
			}
		}
		if !leftToRight {
			for i, j := 0, len(level)-1; i < j; i, j = i+1, j-1 {
				level[i], level[j] = level[j], level[i]
			}
		}
		result = append(result, level)
		leftToRight = !leftToRight // flip direction for the next level
		queue = next
	}
	return result
}

func main() {
	rows := []string{}
	for _, row := range zigzag(buildDemo()) {
		parts := []string{}
		for _, v := range row {
			parts = append(parts, strconv.Itoa(v))
		}
		rows = append(rows, "["+strings.Join(parts, ",")+"]")
	}
	fmt.Println(strings.Join(rows, " ")) // [8] [10,3] [1,6,14] [13,7,4]
}

Time: O(n) · Extra space: O(n). Every node is handled once; reversing a level costs as much as the level is wide, so it adds up to the same total.

Watch out for

  • Pushing children into the queue in a different order on odd levels. Keep the walk the same and only reverse the finished list.
  • Forgetting to flip the flag at the end of every level.
  • Treating the root as a "flip" level. The first level goes left to right.

Quick check

  1. In our tree, what is the second row of the zigzag result?
    • [3,10]
    • [10,3]
    • [1,6,14]
  2. How do we get the zigzag from a normal level order?
    • Reverse every second level
    • Sort every level
    • Use a stack for the whole tree
  3. Which direction is level 3 (1, 6, 14)?
    • Right to left
    • Left to right
    • Random