Discrete StructureUnit 710 min read
Graph Traversal, Trees & Applications: DFS, BFS, Trees, Spanning Trees
Unit 7 of Discrete Structure covers graph traversal algorithms (DFS and BFS), tree structures (binary trees, spanning trees), their applications in real-world systems, and how to analyze and compare them for efficiency and use cases.
TAKEAWAYS:
- Graph traversal (DFS and BFS) explores nodes systematically, with DFS using recursion/depth-first and BFS using queues/level-order.
- Trees are acyclic connected graphs with hierarchical relationships, used to model nested structures like file systems or organizational charts.
- Spanning trees connect all vertices with minimal edges, critical for network design (e.g., minimizing cable costs in NTC’s fiber-optic backbone).
- Applications include pathfinding (Pathao’s ride routing), dependency resolution (Khalti’s transaction validation), and hierarchical data storage (Daraz’s product categories).
- Time complexity differs: BFS is for level-order, while DFS is but may use more memory for recursion stacks.
- Real-world tie: NEPSE’s stock price updates use tree structures to organize nested market data efficiently.
Graph Traversal: DFS and BFS
Graph traversal visits every node in a graph systematically. Two primary methods:
- Depth-First Search (DFS): Explores as far as possible along a branch before backtracking.
- Breadth-First Search (BFS): Explores all neighbors at the present depth before moving deeper.
How DFS Works
DFS uses a stack (implicitly via recursion or explicitly via a stack data structure). It marks nodes as visited to avoid cycles. Steps:
- Start at a root node, mark it visited.
- Push its unvisited neighbors onto the stack.
- Pop a node, process it, and repeat for its neighbors.
Worked Example: Pathao’s Ride Routing Pathao’s algorithm uses DFS to explore possible routes from a rider’s location to destinations, prioritizing shortest paths by depth. Suppose a rider is at Thapathali and wants to reach Koteshwor. The graph represents streets as edges:
Thapathali --(5 min)--> Kalanki
Thapathali --(3 min)--> Bhatbhateni
Kalanki --(7 min)--> Koteshwor
Bhatbhateni --(4 min)--> Koteshwor
DFS Trace:
- Start at Thapathali → visit Kalanki (5 min) → visit Koteshwor (12 min total).
- Backtrack to Thapathali → visit Bhatbhateni (3 min) → visit Koteshwor (7 min total). Optimal path: Thapathali → Bhatbhateni → Koteshwor (7 min).
How BFS Works
BFS uses a queue to explore nodes level by level. It guarantees the shortest path in unweighted graphs. Steps:
- Start at the root, enqueue it.
- Dequeue a node, process it, and enqueue its unvisited neighbors.
- Repeat until the queue is empty.
Worked Example: NTC’s Network Packet Routing NTC’s fiber-optic network uses BFS to route data packets efficiently. Suppose nodes are routers, and edges are fiber links with equal latency. To send a packet from Router A to Router E:
A -- B -- C -- E
A -- D -- E
BFS Trace:
- Enqueue A → dequeue A, enqueue B and D.
- Dequeue B, enqueue C.
- Dequeue D, enqueue E (target found). Shortest path: A → D → E (2 hops).
Comparison Table: DFS vs. BFS
| Feature | DFS | BFS |
|---|---|---|
| Data Structure | Stack (LIFO) | Queue (FIFO) |
| Memory Usage | Lower (no need to store all levels) | Higher (stores all nodes at current level) |
| Path Found | Not necessarily shortest | Shortest in unweighted graphs |
| Use Case | Maze solving, topological sorting | GPS navigation, social network connections |
| Time Complexity |
Trees in Graph Theory
A tree is a connected acyclic graph. Key properties:
- N-1 edges for N nodes.
- No cycles.
- Unique path between any two nodes.
Types of Trees
- Binary Tree: Each node has at most 2 children.
- Spanning Tree: Subgraph of a connected graph that includes all vertices with minimal edges.
- Minimum Spanning Tree (MST): Spanning tree with the smallest total edge weight (used in Kruskal’s/Prim’s algorithms).
Worked Example: NEPSE’s Stock Market Hierarchy NEPSE organizes stocks into hierarchical categories (e.g., Banking, Hydro, Insurance). This forms a tree:
Root: NEPSE
├── Banking: NMB, NBL, Global IME
├── Hydro: Nepal Electricity Authority
└── Insurance: NIC Asia, Siddhartha
Why a Tree?
- Ensures no cycles (e.g., a stock can’t belong to both Banking and Hydro).
- Efficient lookup: To find all banking stocks, traverse the "Banking" subtree.
Applications of Trees
- File Systems: Directories and subdirectories form trees (e.g., Windows Explorer).
- Organizational Charts: Employees report to managers in hierarchical trees.
- Decision Trees: Used in machine learning (e.g., classifying loan applicants in banks like NMB).
Spanning Trees and Applications
A spanning tree connects all vertices of a graph with the fewest edges. For weighted graphs, the Minimum Spanning Tree (MST) minimizes total edge weight.
Kruskal’s Algorithm (Greedy Approach)
- Sort all edges by weight.
- Add the smallest edge that doesn’t form a cycle.
- Repeat until edges are added.
Worked Example: NTC’s Fiber-Optic Network NTC wants to connect 4 cities (A, B, C, D) with fiber links:
- A-B: 5 km
- A-C: 3 km
- B-C: 2 km
- C-D: 4 km
- B-D: 1 km
Kruskal’s Steps:
- Sort edges: B-D (1), B-C (2), A-C (3), C-D (4), A-B (5).
- Add B-D (1 km).
- Add B-C (2 km). Total: 3 km.
- Add A-C (3 km). Total: 6 km.
- Stop (3 edges for 4 nodes). MST: B-D, B-C, A-C (total 6 km).
Prim’s Algorithm (Greedy, Vertex-Centric)
- Start at any vertex, add its smallest edge.
- From the growing tree, add the smallest edge connecting a new vertex.
- Repeat until all vertices are included.
Comparison: Kruskal vs. Prim
| Feature | Kruskal’s Algorithm | Prim’s Algorithm |
|---|---|---|
| Approach | Edge-focused | Vertex-focused |
| Data Structure | Union-Find (Disjoint Set) | Priority Queue (Min-Heap) |
| Use Case | Sparse graphs | Dense graphs |
| Time Complexity | (with Union-Find) |
Real-World Applications
1. Pathao’s Ride Matching
- Graph: Riders and drivers as nodes; edges represent possible matches based on location/time.
- Traversal: BFS finds the nearest available driver to a rider’s request, ensuring efficiency.
- Tree: Decision tree for fare calculation (e.g., base fare + distance + time).
2. Khalti’s Transaction Validation
- Graph: Transactions as nodes; edges represent dependencies (e.g., a payment must confirm before a withdrawal).
- Traversal: DFS validates transaction chains recursively to prevent fraud.
- Tree: Hierarchy of transaction types (e.g., peer-to-peer, merchant payments).
3. Daraz’s Product Catalog
- Tree: Categories (Electronics → Mobile → Smartphones) for efficient search.
- Traversal: BFS to explore all subcategories when a user searches for "phones."
4. NTC’s Network Redundancy
- Spanning Tree: Ensures backup paths if a fiber link fails (e.g., in Kathmandu-Pokhara route).
- Algorithm: Prim’s to minimize cable costs while ensuring connectivity.
5. NEPSE’s Stock Price Updates
- Tree: Organizes stocks by sector for quick updates (e.g., all banking stocks update simultaneously).
- Traversal: DFS to propagate price changes through the hierarchy.
Exam Tip
Understand the Difference Between DFS and BFS:
- DFS uses a stack (recursion or explicit stack); BFS uses a queue.
- DFS explores depth-first; BFS explores level-by-level.
- Exam Question: Given a graph, trace DFS and BFS starting from a node. Show the order of visited nodes.
Spanning Trees and MST:
- Know Kruskal’s (sort edges, add smallest) and Prim’s (start at a vertex, add smallest adjacent edge).
- Exam Question: For a given weighted graph, construct the MST using both algorithms and compare their steps.
Applications:
- Relate traversal algorithms to real-world systems (e.g., Pathao’s BFS for ride matching, NTC’s MST for network design).
- Exam Question: "How would you use DFS/BFS to optimize [X] system?" (e.g., Daraz’s product search).
Time Complexity:
- Both DFS and BFS are , but BFS uses more memory for large graphs.
- Exam Question: "Why is BFS preferred for finding the shortest path in unweighted graphs?"
Tree Properties:
- Memorize: A tree with nodes has edges and is acyclic.
- Exam Question: "Prove that a graph with nodes and edges must contain at least one cycle."
Visual Proofs:
- Draw graphs for traversal examples. Label nodes/edges clearly.
- For spanning trees, show the original graph and the MST side by side.
Key Formula to Remember: For a connected graph with vertices and edges:
- A spanning tree has exactly edges.
- If , the graph contains at least one cycle.
Based on the TU BIM syllabus for Discrete Structure (IT235), unit 7.
Discussion
Loading…