What if your family tree can't show all your friends and their friends? That's why graphs exist!
Why Graphs Exist and What Trees Cannot Model in DSA Typescript - The Real Reason
Imagine you want to map all the roads connecting cities in a country. You try to draw it like a family tree, but soon realize many cities connect back and forth, not just in a straight line.
Using a tree-like structure here is slow and confusing because trees only allow one path between points. Roads often loop and connect in many ways, so trees can't show all connections properly.
Graphs let you connect points in any way you want. They can show loops, multiple paths, and complex networks easily, making it perfect for mapping roads, social networks, or web links.
class TreeNode { value: string; children: TreeNode[]; constructor(value: string) { this.value = value; this.children = []; } } // Trying to connect cities with multiple roads is hard here
class Graph { adjacencyList: Map<string, string[]> = new Map(); addEdge(city1: string, city2: string) { if (!this.adjacencyList.has(city1)) this.adjacencyList.set(city1, []); this.adjacencyList.get(city1)!.push(city2); if (!this.adjacencyList.has(city2)) this.adjacencyList.set(city2, []); this.adjacencyList.get(city2)!.push(city1); } } // Easily connect cities with many roads
Graphs let us model real-world networks with complex connections that trees simply cannot represent.
Social media platforms use graphs to show how friends connect, follow, and interact with each other in many ways, not just in a simple hierarchy.
Trees only allow one path between points, limiting complex connections.
Graphs support loops and multiple connections, modeling real networks.
Graphs are essential for representing roads, social networks, and web links.