function inorder(node: Node | null, output: number[]) {if (node === null) return;
inorder(node.left, output);
output.push(node.key);
inorder(node.right, output);
}
function preorder(node: Node | null, output: number[]) {if (node === null) return;
output.push(node.key);
preorder(node.left, output);
preorder(node.right, output);
}
function postorder(node: Node | null, output: number[]) {if (node === null) return;
postorder(node.left, output);
postorder(node.right, output);
output.push(node.key);
}
function levelorder(root: Node | null, output: number[]) {const queue = root ? [root] : [];
while (queue.length > 0) {const node = queue.shift()!;
output.push(node.key);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
In-order: left subtree, node, right subtree. On a BST this yields the keys sorted.
Understanding Traversals
The idea
A traversal visits every node once; the order in which a node is visited relative to its subtrees is what changes. In-order visits the left subtree, the node, then the right subtree, which on a binary search tree yields the keys sorted. Pre-order visits the node first, which is the order that lets you rebuild the tree. Post-order visits children before the parent, the order for freeing memory or evaluating an expression tree.
The three recursive traversals differ only in where the visit line sits. Level-order is different in kind: it uses a queue instead of the call stack, and reads the tree one depth at a time, which is breadth-first search applied to a tree.
The four stages
Complexity
Versus its siblings
Pseudocode
INORDER(node): if node ≠ null: INORDER(left); visit(node); INORDER(right)
PREORDER(node): if node ≠ null: visit(node); PREORDER(left); PREORDER(right)
POSTORDER(node): if node ≠ null: POSTORDER(left); POSTORDER(right); visit(node)
LEVELORDER(root)
queue ← [root]
while queue not empty
node ← dequeue; visit(node); enqueue its children
When to use
Pitfalls
History
The names pre-order, in-order and post-order were fixed by Knuth in the first volume of The Art of Computer Programming in 1968, where he also traced threaded trees back to Perlis and Thornton in 1960. Morris showed in 1979 that in-order can run in constant extra space by temporarily rewiring right pointers.