0
0
DSA Typescriptprogramming~3 mins

Why Graphs Exist and What Trees Cannot Model in DSA Typescript - The Real Reason

Choose your learning style9 modes available
The Big Idea

What if your family tree can't show all your friends and their friends? That's why graphs exist!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
class TreeNode {
  value: string;
  children: TreeNode[];
  constructor(value: string) {
    this.value = value;
    this.children = [];
  }
}
// Trying to connect cities with multiple roads is hard here
After
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
What It Enables

Graphs let us model real-world networks with complex connections that trees simply cannot represent.

Real Life Example

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.

Key Takeaways

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.