Concept Flow - Why Graphs Exist and What Trees Cannot Model
Start: Need to model relationships
Use Tree?
Tree models
Hierarchical
No cycles
This flow shows why we choose trees for simple hierarchies but need graphs for complex, cyclic relationships.
class Graph {
Map<String, List<String>> adjList = new HashMap<>();
void addEdge(String u, String v) {
adjList.computeIfAbsent(u, k -> new ArrayList<>()).add(v);
adjList.computeIfAbsent(v, k -> new ArrayList<>()).add(u);
}
}| Step | Operation | Nodes in Graph | Edges Added | Visual State |
|---|---|---|---|---|
| 1 | Create empty graph | {} | None | {} |
| 2 | Add edge A-B | {A, B} | A-B | {A: [B], B: [A]} |
| 3 | Add edge B-C | {A, B, C} | B-C | {A: [B], B: [A, C], C: [B]} |
| 4 | Add edge C-A | {A, B, C} | C-A | {A: [B, C], B: [A, C], C: [B, A]} |
| 5 | Add edge B-D | {A, B, C, D} | B-D | {A: [B, C], B: [A, C, D], C: [B, A], D: [B]} |
| 6 | Add edge D-E | {A, B, C, D, E} | D-E | {A: [B, C], B: [A, C, D], C: [B, A], D: [B, E], E: [D]} |
| 7 | Add edge E-B | {A, B, C, D, E} | E-B | {A: [B, C], B: [A, C, D, E], C: [B, A], D: [B, E], E: [D, B]} |
| 8 | Graph now has cycles | {A, B, C, D, E} | Cycle edges | Graph with cycles visible |
| 9 | Compare with tree | Tree cannot model cycles | No cycles | Tree structure limited |
| 10 | End | Graph models complex relations | N/A | Graph suitable for networks |
| Variable | Start | After 2 | After 3 | After 4 | After 5 | After 6 | After 7 | Final |
|---|---|---|---|---|---|---|---|---|
| adjList | {} | {A: [B], B: [A]} | {A: [B], B: [A, C], C: [B]} | {A: [B, C], B: [A, C], C: [B, A]} | {A: [B, C], B: [A, C, D], C: [B, A], D: [B]} | {A: [B, C], B: [A, C, D], C: [B, A], D: [B, E], E: [D]} | {A: [B, C], B: [A, C, D, E], C: [B, A], D: [B, E], E: [D, B]} | {A: [B, C], B: [A, C, D, E], C: [B, A], D: [B, E], E: [D, B]} |
Graphs model complex relationships including cycles. Trees model simple hierarchies without cycles. Graphs use nodes and edges; edges can connect any nodes. Trees have parent-child links only, no loops. Use graphs for networks, social links, roads. Use trees for clear hierarchical data.
import java.util.*;
public class GraphExample {
public static void main(String[] args) {
HashMap graph = new HashMap<>();
graph.put(1, Arrays.asList(2, 3));
graph.put(2, Arrays.asList(1, 4));
graph.put(3, Arrays.asList(1));
graph.put(4, Arrays.asList(2));
for (int node : graph.keySet()) {
System.out.print(node + " -> ");
for (int neighbor : graph.get(node)) {
System.out.print(neighbor + " ");
}
System.out.println();
}
}
}
What is the output of this program?void addEdge(HashMap graph, int u, int v) {
graph.get(u).add(v);
graph.get(v).add(u);
}Pass the test and this pattern moves unknown