Master Depth-First Search (DFS) tree traversals: pre-order, in-order (sorted BST sequence), and post-order node evaluation.
Learn how dynamic arrays achieve O(1) amortized insertion, contiguous memory layout, and geometric doubling strategies.
Traversing a tree means visiting every node once in a deterministic order. Depth-First Search (DFS) explores down a branch as deep as possible before backtracking.
The name specifies WHEN the current root node is processed relative to its left and right subtrees:
4
/ \
2 5
/ \
1 3
Pre-order: [ 4, 2, 1, 3, 5 ]
In-order: [ 1, 2, 3, 4, 5 ] ◄── Sorted order on BST!
Post-order: [ 1, 3, 2, 5, 4 ]
// In-order Traversal: Left -> Node -> Right
function inOrderTraversal(root, result = []) {
if (!root) return result;
inOrderTraversal(root.left, result); // 1. Traverse left subtree
result.push(root.val); // 2. Visit current node
inOrderTraversal(root.right, result); // 3. Traverse right subtree
return result;
}
// Pre-order Traversal: Node -> Left -> Right
function preOrderTraversal(root, result = []) {
if (!root) return result;
result.push(root.val);
preOrderTraversal(root.left, result);
preOrderTraversal(root.right, result);
return result;
}
Use in-order for BST validation. Next, let's explore Breadth-First Search (BFS) Level-Order Traversal!