Unit 05

Graphs

Where a tree forces strict hierarchy, a graph lets any node connect to any other. That flexibility is exactly what's needed to model real networks: roads, friendships, dependencies, the internet itself.

A B C D E A–B–D–A forms a cycle — something a tree can never have

// nodes (vertices) connected by edges, with no single root and no restriction on connections

What it is

A graph is a set of nodes (often called vertices) connected by edges. Edges can be directed (one-way, like a "follows" relationship) or undirected (two-way, like a road), and can optionally carry a weight (like distance or cost). Unlike a tree, a graph can have cycles and no node needs to be the "root."

Why it's useful

Where it struggles

Time complexity (adjacency list representation)

OperationTime
Add vertexO(1)
Add edgeO(1)
BFS / DFS traversalO(V + E)
Check if edge existsO(degree of vertex)

Quick check

← Trees & BSTs Next: Hashing →