Structures
What the structures look like
Before you solve a graph or tree problem, you should be able to picture it. Each structure below has a drawing, its vocabulary, how it is stored in code, what it costs, and the wording that tells you a problem is about it. For stack, queue, map and other library containers, see the Reference.
Graph
A graph is dots (nodes, also called vertices) joined by lines (edges). It models anything connected: cities and roads, people and friendships, courses and prerequisites, cells in a grid. Unlike a tree, a graph can have loops, and its nodes need not all be reachable from one place.
Words you will meet
- Node / vertex
- One dot. Usually numbered 0 to n - 1.
- Edge
- A line between two nodes. Written (u, v).
- Neighbour
- A node you can reach straight from another node by one edge.
- Directed
- Edges are arrows: you can go u to v but not back. Think one-way streets.
- Weighted
- Each edge has a cost or distance.
- Path
- A walk from one node to another along edges.
- Cycle
- A path that returns to its start.
- Connected
- Every node can be reached from every other (undirected). A graph can also split into several separate pieces, called components.
- Degree
- How many edges touch a node.
How it looks in code
Store it as an adjacency list (the usual choice): for each node, the list of its neighbours
Java
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) g.add(new ArrayList<>());
g.get(u).add(v); // edge u -> v
g.get(v).add(u); // add this line too if undirectedC++
vector<vector<int>> g(n);
g[u].push_back(v); // edge u -> v
g[v].push_back(u); // add this line too if undirectedPython
g = [[] for _ in range(n)]
g[u].append(v) # edge u -> v
g[v].append(u) # add this line too if undirectedWeighted: store (neighbour, cost) pairs
Java
List<List<int[]>> g = new ArrayList<>();
// ... same setup ...
g.get(u).add(new int[]{v, w});C++
vector<vector<pair<int,int>>> g(n);
g[u].push_back({v, w});Python
g[u].append((v, w))Or as an adjacency matrix: a table where cell [u][v] says whether the edge exists (fine for small n)
Java
int[][] m = new int[n][n];
m[u][v] = 1;C++
vector<vector<int>> m(n, vector<int>(n, 0));
m[u][v] = 1;Python
m = [[0] * n for _ in range(n)]
m[u][v] = 1Always keep a visited marker so a cycle does not trap you
Java
boolean[] seen = new boolean[n];C++
vector<bool> seen(n, false);Python
seen = [False] * nWhat it can do, and the cost
- Add an edge: O(1) in a list
- Neighbours of u: O(degree of u) in a list, O(n) in a matrix
- Is there an edge u-v?: O(degree) in a list, O(1) in a matrix
- Visit every node and edge (BFS or DFS): O(V + E)
- Memory: O(V + E) list, O(V squared) matrix
How to spot it in a problem
- Things connected to each other: friends, roads, links, dependencies, prerequisites.
- "Number of islands", "connected", "reachable", "shortest path", "order of tasks".
- A grid where you move up, down, left and right: each cell is a node and its four neighbours are its edges.
- You are given a list of pairs [a, b]: those pairs are the edges.
Binary tree
A tree is a graph with no cycles, drawn from the top down. One node is the root. Every other node hangs below exactly one parent. In a binary tree each node has at most two children, called left and right.
Words you will meet
- Root
- The top node. The only one with no parent.
- Leaf
- A node with no children.
- Parent / child
- The node above / below a node.
- Depth of a node
- How many edges from the root down to it.
- Height of the tree
- The longest root-to-leaf path. Written with edges or nodes, so check the problem's wording.
- Subtree
- A node together with everything below it. Most tree solutions work by solving the left and right subtrees and combining them.
How it looks in code
A node holds a value and two child links (null / nullptr / None means no child)
Java
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) { val = v; }
}C++
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = rightWhat it can do, and the cost
- Preorder (node, left, right) / inorder (left, node, right) / postorder (left, right, node): O(n)
- Level order (row by row, uses a queue): O(n)
- Height, count nodes, sum: O(n)
- Memory for recursion: O(height): about log n if balanced, n if it leans like a stick
How to spot it in a problem
- You are given a node called root with left and right.
- Words like depth, height, path from root, ancestor, leaf, level, subtree, symmetric.
- The answer for a node depends on the answers for its left and right children: recursion.
Binary search tree
A binary tree with one rule at every node: everything in the left subtree is smaller, everything in the right subtree is larger. So you can find a value like a binary search: go left if smaller, right if bigger.
Words you will meet
- Ordering rule
- left < node < right, at every node, not only the root's children.
- Inorder walk
- Visiting left, node, right gives the values in sorted order. This fact solves many BST problems.
- Balanced
- Both sides are about the same height. Then everything is O(log n). A BST built from sorted input leans into a stick and becomes O(n).
How it looks in code
Same node as a binary tree. The rule lives in how you insert and search, not in the node.
Java
TreeNode cur = root;
while (cur != null && cur.val != target)
cur = target < cur.val ? cur.left : cur.right;C++
TreeNode* cur = root;
while (cur != nullptr && cur->val != target)
cur = target < cur->val ? cur->left : cur->right;Python
cur = root
while cur and cur.val != target:
cur = cur.left if target < cur.val else cur.rightWhat it can do, and the cost
- Search, insert, delete: O(height): O(log n) balanced, O(n) worst case
- Smallest / largest: Keep going left / right
- Sorted list of all values: Inorder walk, O(n)
How to spot it in a problem
- The statement says binary search tree or BST.
- Smaller to the left, larger to the right.
- "Kth smallest", "validate", "closest value", "inorder successor".
Heap (priority queue)
A tree where every parent is smaller than its children (a min heap) or larger (a max heap). The smallest (or largest) value is therefore always at the top, and you can take it out quickly. It is drawn as a tree but stored in a plain array.
Words you will meet
- Index rule
- In the array, the children of index i sit at 2i + 1 and 2i + 2. The parent of i is (i - 1) / 2, whole-number division.
- Sift up / down
- After adding at the end you swap upward while smaller than the parent. After removing the top you move the last item to the top and swap downward.
- Not sorted
- Only the top is guaranteed. The rest is only partly ordered.
How it looks in code
You rarely write a heap yourself: use the library one (see the Reference page for push, pop and peek)
Java
PriorityQueue<Integer> pq = new PriorityQueue<>(); // min heap
pq.offer(5); int top = pq.poll();C++
priority_queue<int, vector<int>, greater<int>> pq; // min heap
pq.push(5); int top = pq.top(); pq.pop();Python
import heapq
h = []
heapq.heappush(h, 5); top = heapq.heappop(h)What it can do, and the cost
- Push: O(log n)
- Pop the top: O(log n)
- Peek the top: O(1)
- Build from n items: O(n)
How to spot it in a problem
- "Kth largest" or "kth smallest", "top k", "k closest".
- Repeatedly take the best remaining item while new items keep arriving.
- Merge k sorted lists, running median, task scheduling.
Trie (prefix tree)
A tree that stores words letter by letter. Words that share a beginning share a path, so asking "does any word start with this prefix?" is just walking down the letters.
Words you will meet
- Root
- An empty node. Every word starts below it.
- Edge letter
- Each step down is one letter.
- End marker
- A flag on the node where a stored word finishes. "te" is a prefix here but not a word.
How it looks in code
Each node has up to 26 children (for lowercase letters) and an end flag
Java
class TrieNode {
TrieNode[] next = new TrieNode[26];
boolean end;
}C++
struct TrieNode {
TrieNode* next[26] = {nullptr};
bool end = false;
};Python
class TrieNode:
def __init__(self):
self.next = {} # letter -> TrieNode
self.end = FalseWhat it can do, and the cost
- Insert a word of length L: O(L)
- Search a word or prefix: O(L)
- Memory: up to 26 times the total letters
How to spot it in a problem
- Many words and questions about prefixes.
- Autocomplete, word dictionary, "starts with", word search on a board.
- Hash set of words is too slow for the prefix questions.
Union-Find (disjoint sets)
Keeps track of groups. Each group is a tiny tree and the root of the tree is the group's name. Two operations: find (which group is this item in?) and union (merge two groups). It answers "are these two connected?" very quickly while edges are being added.
Words you will meet
- parent array
- parent[i] is the item above i. A root points to itself.
- find(x)
- Climb parents until you reach a root. Path compression: point everything you passed straight at the root, so later finds are faster.
- union(a, b)
- find both roots; if they differ, hang one root under the other.
How it looks in code
Setup and find with path compression
Java
int[] parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}C++
vector<int> parent(n);
for (int i = 0; i < n; i++) parent[i] = i;
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}Python
parent = list(range(n))
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]What it can do, and the cost
- find and union: almost O(1) each (inverse Ackermann, in practice a tiny constant)
- Memory: O(n)
How to spot it in a problem
- Edges arrive one by one and you must tell if two nodes are already connected.
- Count connected groups, detect a cycle in an undirected graph, accounts merge, redundant connection.
- Grouping by a relation like "same as".