Graphs and Trees
Explore the fundamental structures of graph theory: vertices, edges, paths, and trees. Essential for modeling networks, relationships, and hierarchies.
- Understand graph terminology
- Represent graphs using matrices and lists
- Perform BFS and DFS traversals
- Identify Euler and Hamilton paths
- Work with trees and spanning trees
- Apply shortest path algorithms
1. Graph Basics
A graph consists of vertices V and edges E.
In an undirected graph, edges are unordered pairs. In a directed graph, edges are ordered pairs.
Each edge contributes 2 to the sum of degrees.
- Adjacent: Vertices connected by an edge
- Degree: Number of edges incident to a vertex
- Path: Sequence of vertices connected by edges
- Cycle: Path that starts and ends at the same vertex
- Connected: Path exists between every pair of vertices
2. Graph Traversals
BFS (Breadth-First Search): Explores level by level using a queue.
DFS (Depth-First Search): Explores as deep as possible using a stack.
BFS:
- Shortest path (unweighted)
- Level-order traversal
DFS:
- Cycle detection
- Topological sorting
3. Euler and Hamilton Paths
An Euler path visits every edge exactly once.
An Euler circuit is an Euler path that returns to the start.
- Euler circuit: All vertices have even degree
- Euler path: Exactly 2 vertices have odd degree
A Hamilton path visits every vertex exactly once.
Finding Hamilton paths is NP-complete (no efficient algorithm known).
4. Trees
A tree is a connected graph with no cycles.
Equivalent: connected with n-1 edges, or unique path between any two vertices.
- A tree with n vertices has exactly n-1 edges
- Adding any edge creates exactly one cycle
- Removing any edge disconnects the tree
A spanning tree of a connected graph G is a subgraph that is a tree containing all vertices of G.
5. Shortest Paths
Finds shortest paths from source to all vertices:
- Initialize distances: source = 0, others = ∞
- Pick unvisited vertex with minimum distance
- Update distances to neighbors
- Repeat until all visited
Complexity: O(V²) or O((V+E) log V) with priority queue.
6. Graph Coloring
A proper vertex coloring assigns colors so no adjacent vertices share a color.
The chromatic number χ(G) is the minimum colors needed.
Every planar graph can be colored with at most 4 colors.
Practice Quiz
Frequently Asked Questions
When should I use BFS vs DFS?
BFS: Shortest path, level-by-level exploration.
DFS: Path finding, cycle detection, topological sort.
What's the difference between a tree and a graph?
A tree is a connected graph with no cycles—it has exactly n-1 edges for n vertices.
Why is the Hamilton path problem hard?
Unlike Euler paths (polynomial time), Hamilton paths are NP-complete—no efficient algorithm exists.
What are common applications of graphs?
Social networks, road maps, web links, dependency management, circuit design.