Module 3 · Lesson 1 · ~25 min
In real engineering, linked lists are rare. In interviews, they're a vehicle for testing pointer manipulation. Trees, on the other hand, are everywhere — file systems, the DOM, JSON, ASTs. This lesson is the muscle memory both require.
A singly-linked list node is two fields: a value and a pointer to the next node. Watch it animate.
Three skills make every linked-list problem easy:
dummy.next. Saves you ten special cases.The classic: reverse a linked list. Three pointers, walk through once.
def reverse(head):
prev, curr = None, head
while curr:
nxt = curr.next # save the next node before we clobber it
curr.next = prev # reverse this link
prev = curr # move prev forward
curr = nxt # move curr forward
return prev
# O(n) time, O(1) space
function reverse(head) {
let prev = null, curr = head;
while (curr) {
const nxt = curr.next; // save the next node before we clobber it
curr.next = prev; // reverse this link
prev = curr; // move prev forward
curr = nxt; // move curr forward
}
return prev;
}
// O(n) time, O(1) space
function reverse(head: Node | null): Node | null {
let prev: Node | null = null, curr = head;
while (curr) {
const nxt: Node | null = curr.next; // save the next node before we clobber it
curr.next = prev; // reverse this link
prev = curr; // move prev forward
curr = nxt; // move curr forward
}
return prev;
}
// O(n) time, O(1) space
A binary tree node is a value plus left/right child pointers. A general tree node has a list of children. The most common tree in interviews is the binary tree, and the most common operation is traversal.
| Traversal | Order | Implementation | Use case |
|---|---|---|---|
| Preorder | node, left, right | recursive, or stack with right-first push | copy a tree, serialize |
| Inorder | left, node, right | recursive, or stack with leftmost-walk | BST → sorted output |
| Postorder | left, right, node | recursive, or two-stack trick | delete a tree, evaluate expression |
| Level-order (BFS) | level by level | queue | shortest path, "by level" problems |
Inorder traversal of a binary search tree visits values in ascending sorted order. This is the trick behind "validate a BST," "kth smallest element in a BST," and a dozen other problems.
When you write a recursive function over a binary tree, the recursion's call tree is the tree. f(node) calls f(node.left) and f(node.right), exactly mirroring the structure.
So the time complexity of a tree traversal is O(n), where n is the number of nodes — each node is visited exactly once, doing O(1) work. The space complexity is O(h), where h is the height of the tree, because that's how deep the call stack goes. For balanced trees h = log n; for a skewed tree (basically a linked list) h = n.