Loading...
Tree traversal algorithms and patterns
Section 1 of 4
Tree traversal is the process of visiting each node in a tree data structure exactly once. The order in which nodes are visited defines different traversal algorithms, each useful for different purposes.
function inorderTraversal(root) {
const result = [];
function inorder(node) {
if (node) {
inorder(node.left); // Left
result.push(node.val); // Root
inorder(node.right); // Right
}
}
inorder(root);
return result;
}Level-order traversal visits nodes level by level, from left to right. It uses a queue data structure to keep track of nodes to visit next.
function levelorderTraversal(root) {
if (!root) return [];
const result = [];
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
result.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return result;
}function iterativeInorder(root) {
const result = [];
const stack = [];
let current = root;
while (current || stack.length > 0) {
// Go to leftmost node
while (current) {
stack.push(current);
current = current.left;
}
// Process node
current = stack.pop();
result.push(current.val);
// Move to right subtree
current = current.right;
}
return result;
}| Method | Time | Space | Notes |
|---|---|---|---|
| Recursive DFS | O(n) | O(h) | Call stack space |
| Iterative DFS | O(n) | O(h) | Explicit stack |
| Level-order BFS | O(n) | O(w) | Queue space |