Trees Graphs
Tree and graph algorithm patterns for technical coding interviews
You are an expert in tree and graph algorithms for technical interview preparation. ## Key Points - **Binary tree**: each node has at most two children; no inherent ordering unless it is a BST - **Binary search tree (BST)**: left subtree values < node < right subtree values; in-order traversal yields sorted output - **Balanced trees**: AVL, Red-Black — know that they guarantee O(log n) height; rarely need to implement in interviews - **Graph representations**: adjacency list (space-efficient for sparse graphs) vs. adjacency matrix (O(1) edge lookup) - **Directed vs. undirected; weighted vs. unweighted; cyclic vs. acyclic** - **Tree as a special graph**: connected, acyclic, undirected graph with n-1 edges for n nodes - **In-order (left, root, right)**: produces sorted output for BSTs. Iterative version uses a stack. - **Pre-order (root, left, right)**: useful for serialization and copying tree structure. - **Post-order (left, right, root)**: useful for deletion and computing subtree-dependent values (height, size). - **Level-order (BFS)**: use a queue; process nodes level by level. Needed for "level averages," "right side view," zigzag traversal. - **Maximum Depth** (LeetCode 104): return 1 + max(depth(left), depth(right)). - **Diameter of Binary Tree** (LeetCode 543): at each node, the path through it is height(left) + height(right); track the global max.
skilldb get interview-prep-skills/Trees GraphsFull skill: 85 linesTrees & Graphs — Interview Preparation
You are an expert in tree and graph algorithms for technical interview preparation.
Core Philosophy
Overview
Trees and graphs appear in roughly 25-30% of coding interview questions. Trees test recursive thinking and traversal fluency. Graphs test your ability to model relationships and apply BFS/DFS systematically. The key skill is recognizing which traversal order or graph algorithm fits the problem.
Core Concepts
- Binary tree: each node has at most two children; no inherent ordering unless it is a BST
- Binary search tree (BST): left subtree values < node < right subtree values; in-order traversal yields sorted output
- Balanced trees: AVL, Red-Black — know that they guarantee O(log n) height; rarely need to implement in interviews
- Graph representations: adjacency list (space-efficient for sparse graphs) vs. adjacency matrix (O(1) edge lookup)
- Directed vs. undirected; weighted vs. unweighted; cyclic vs. acyclic
- Tree as a special graph: connected, acyclic, undirected graph with n-1 edges for n nodes
Common Patterns
Tree Traversals
- In-order (left, root, right): produces sorted output for BSTs. Iterative version uses a stack.
- Pre-order (root, left, right): useful for serialization and copying tree structure.
- Post-order (left, right, root): useful for deletion and computing subtree-dependent values (height, size).
- Level-order (BFS): use a queue; process nodes level by level. Needed for "level averages," "right side view," zigzag traversal.
Recursive DFS on Trees
Most tree problems follow one template: compute something for left and right subtrees, then combine at the current node.
- Maximum Depth (LeetCode 104): return 1 + max(depth(left), depth(right)).
- Diameter of Binary Tree (LeetCode 543): at each node, the path through it is height(left) + height(right); track the global max.
- Lowest Common Ancestor (LeetCode 236): if current node is p or q, return it; otherwise recurse left and right; if both return non-null, current node is the LCA.
- Validate BST (LeetCode 98): pass min/max bounds down the recursion.
Graph BFS / DFS
- Connected components: iterate all nodes; for each unvisited node, run BFS/DFS and mark everything reachable.
- Shortest path in unweighted graph: BFS from the source; first visit guarantees shortest distance.
- Cycle detection (directed): DFS with three states (unvisited, in-progress, done). A back edge to an in-progress node means a cycle.
- Cycle detection (undirected): DFS or Union-Find; if you reach an already-visited node that is not the parent, there is a cycle.
- Topological sort: Kahn's algorithm (BFS with in-degree tracking) or DFS post-order reversal. Used for task scheduling, course prerequisites (LeetCode 207, 210).
Shortest Path Algorithms
- Dijkstra's: single-source shortest path for non-negative weights. Use a min-heap. O((V + E) log V).
- Bellman-Ford: handles negative weights. O(V * E). Detect negative cycles if relaxation still possible after V-1 iterations.
- BFS on unweighted graphs: equivalent to Dijkstra with all weights = 1.
Union-Find (Disjoint Set Union)
- Efficient for dynamic connectivity: "are these two nodes connected?" and "merge these two groups."
- With path compression + union by rank: nearly O(1) amortized per operation.
- Number of Islands (LeetCode 200): can be solved with Union-Find or simple DFS/BFS.
Practice Strategy
- Draw the tree/graph before writing code. Trace through the algorithm on the drawing.
- Write the recursive template first: base case (null node), recursive calls, combine step.
- Know when to switch from recursion to iteration: deep trees risk stack overflow; use an explicit stack or BFS queue.
- Practice both adjacency list construction and traversal from edge lists — many problems give edges, not a ready-made structure.
- For graph problems, always ask: directed or undirected? weighted? can there be cycles? disconnected components?
Common Mistakes
- Forgetting the visited set in graph traversal, causing infinite loops in cyclic graphs
- Confusing pre-order and post-order when the combine step depends on children's results (must use post-order)
- Not handling null/empty tree as a base case
- Using DFS for shortest-path in an unweighted graph instead of BFS
- Building the adjacency list for only one direction in an undirected graph
- Treating a BST problem as a generic binary tree problem and missing the O(log n) opportunity
Anti-Patterns
Over-engineering for hypothetical scale. Building for millions of users when you have hundreds adds complexity without value. Solve today's problems first.
Ignoring the existing ecosystem. Reinventing functionality that mature libraries already provide well wastes time and introduces unnecessary risk.
Premature abstraction. Creating elaborate frameworks and utilities before you have enough concrete cases to know what the abstraction should look like produces the wrong abstraction.
Neglecting error handling at boundaries. Internal code can trust its inputs, but system boundaries (user input, APIs, file I/O) require defensive validation.
Skipping documentation for obvious code. What is obvious to you today will not be obvious to your colleague next month or to you next year.
Install this skill directly: skilldb add interview-prep-skills
Related Skills
Arrays Strings
Array and string manipulation patterns for technical coding interviews
Behavioral
Behavioral interview preparation using the STAR method and leadership principles
Big O
Time and space complexity analysis for technical coding interviews
Dynamic Programming
Dynamic programming patterns and techniques for technical coding interviews
Linked Lists Stacks
Linked list, stack, and queue patterns for technical coding interviews
SQL Interview
SQL query patterns and database concepts for technical coding interviews