Trees & Graphs
Traversals, recursion on trees, BFS/DFS, shortest paths and connectivity.
9 pages, free to read
- 1
Tree traversals
BeginnerA traversal is a fixed order for visiting every node of a tree once: preorder, inorder and postorder go deep first, level order goes row by row.
9 min read - 2
Binary search trees
BeginnerA binary search tree keeps every left subtree smaller and every right subtree larger than its node, so search, insert and delete follow one path and cost O(height).
10 min read - 3
Recursion on trees (height, diameter, LCA)
IntermediateMost tree problems are solved by asking each subtree a question, trusting the recursive answer, and combining the left and right answers at the node.
11 min read - 4
Representing graphs
BeginnerA graph is nodes plus edges, and you store it as an adjacency list, an adjacency matrix, an edge list, or implicitly as a grid, choosing by size, density and the queries you need.
8 min read - 5
Breadth-first search
IntermediateBFS explores a graph in rings of increasing distance using a queue, so the first time it reaches a node is along a shortest path when all edges cost the same.
10 min read - 6
Depth-first search
IntermediateDFS follows one path as deep as it can before backing up, which makes it the natural tool for exploring regions, finding connected components and detecting cycles.
10 min read - 7
Topological sort
IntermediateA topological sort lists the nodes of a directed acyclic graph so that every edge points forward, giving a valid order for tasks with dependencies, and it exists only if there is no cycle.
10 min read - 8
Shortest paths (Dijkstra)
AdvancedDijkstra's algorithm finds the cheapest path from one source to every node when edge weights are non-negative, by always settling the closest unsettled node next using a min-heap.
12 min read - 9
Union-find (disjoint sets)
IntermediateUnion-find keeps track of which items belong to the same group and merges groups in nearly constant time, using a parent pointer per item, path compression and union by size.
10 min read