AI EducademyAIEducademy
๐ŸŒณ

AI Foundations

๐ŸŒฑ
AI Seeds

Start from zero

๐ŸŒฟ
AI Sprouts

Build foundations

๐ŸŒณ
AI Branches

Apply in practice

๐Ÿ•๏ธ
AI Canopy

Go deep

๐ŸŒฒ
AI Forest

Master AI

๐Ÿ”จ

AI Mastery

โœ๏ธ
AI Sketch

Start from zero

๐Ÿชจ
AI Chisel

Build foundations

โš’๏ธ
AI Craft

Apply in practice

๐Ÿ’Ž
AI Polish

Go deep

๐Ÿ†
AI Masterpiece

Master AI

๐Ÿš€

Career Ready

๐Ÿš€
Interview Launchpad

Start your journey

๐ŸŒŸ
Behavioral Mastery

Master soft skills

๐Ÿ’ป
Technical Interviews

Ace the coding round

๐Ÿค–
AI & ML Interviews

ML interview mastery

๐Ÿ†
Offer & Beyond

Land the best offer

View All Programsโ†’

Lab

7 experiments loaded
๐Ÿง Neural Network Playground๐Ÿค–AI or Human?๐Ÿ’ฌPrompt Lab๐ŸŽจImage Generator๐Ÿ˜ŠSentiment Analyzer๐Ÿ’กChatbot Builderโš–๏ธEthics Simulator
๐ŸŽฏMock InterviewEnter the Labโ†’
JourneyBlog
๐ŸŽฏ
About

Making AI education accessible to everyone, everywhere

โ“
FAQ

Common questions answered

โœ‰๏ธ
Contact

Get in touch with us

โญ
Open Source

Built in public on GitHub

Get Started
AI EducademyAIEducademy

MIT Licence. Open Source

Learn

  • Academics
  • Lessons
  • Lab

Community

  • GitHub
  • Contribute
  • Code of Conduct
  • About
  • FAQ

Support

  • Buy Me a Coffee โ˜•
  • Terms of Service
  • Privacy Policy
  • Contact
AI & Engineering Academicsโ€บโœ๏ธ AI Sketchโ€บLessonsโ€บTrees and Graphs Visualised
๐ŸŒณ
AI Sketch โ€ข Intermediateโฑ๏ธ 18 min read

Trees and Graphs Visualised

Data With Relationships

So far, we've looked at data in lines - arrays, linked lists, stacks, and queues all arrange items in a sequence. But the real world isn't linear. Family trees branch out. Social networks form webs. Road maps create interconnected routes.

Trees and graphs capture these relationships, and they're at the heart of some of AI's most powerful techniques.

Trees - Hierarchical Data

A tree is a structure where each item (called a node) can have child nodes, forming a hierarchy. There's one special node at the top called the root, and nodes with no children are called leaves.

         CEO
        /    \
      CTO    CFO
     /   \      \
   Dev1  Dev2   Accountant
A tree structure with a root node branching into child nodes across three levels, alongside a graph with interconnected nodes
Trees flow downward from a root; graphs connect nodes in any direction.

Trees Are Everywhere

  • File systems: Folders contain subfolders which contain files - a tree.
  • HTML/DOM: Every web page is a tree of nested elements.
  • Organisation charts: Managers have reports who may have their own reports.
  • JSON data: The nested structure of JSON is fundamentally a tree.

Binary Trees

A binary tree restricts each node to at most two children - a left child and a right child. This simple constraint enables powerful algorithms.

        8
       / \
      3   10
     / \    \
    1   6    14

Binary Search Trees (BSTs)

A binary search tree adds one rule: for every node, all values in the left subtree are smaller, and all values in the right subtree are larger.

This makes searching fast - at each node, you know whether to go left or right:

Find 6 in the BST above:
  Start at 8 โ†’ 6 < 8, go left
  At 3 โ†’ 6 > 3, go right
  At 6 โ†’ Found it!
Lesson 5 of 100% complete
โ†Linked Lists and Stacks

Discussion

Sign in to join the discussion

Suggest an edit to this lesson

Time complexity: O(log n) for a balanced tree - the same logarithmic magic as binary search on a sorted array.

๐Ÿง Quick Check

In a balanced binary search tree with 1,000,000 nodes, roughly how many comparisons are needed to find a value?

Graphs - Everything Connected

A graph generalises trees by removing the hierarchy constraint. It consists of nodes (also called vertices) and edges (connections between nodes). Edges can be:

  • Directed (one-way: A โ†’ B) or undirected (two-way: A โ†” B)
  • Weighted (each edge has a cost/distance) or unweighted
Social network (undirected):
  Alice - Bob - Charlie
    \       |
     Diana - Eve

Road map (weighted, directed):
  London โ†’(2h)โ†’ Birmingham โ†’(1.5h)โ†’ Manchester

Graphs Are Everywhere

  • Social networks: People are nodes; friendships are edges.
  • The internet: Web pages are nodes; hyperlinks are edges.
  • Road maps: Intersections are nodes; roads are edges with distance weights.
  • Recommendation systems: Users and products are nodes; interactions are edges.
๐Ÿคฏ

Facebook's social graph contains over 3 billion nodes (users) and hundreds of billions of edges (friendships). Graph algorithms determine your News Feed, friend suggestions, and ad targeting - all running on one of the largest graphs ever built.

How AI Uses Trees

Decision Trees

One of the most interpretable AI models is the decision tree. It asks a series of yes/no questions to classify data:

Is temperature > 30ยฐC?
โ”œโ”€โ”€ Yes: Is humidity > 70%?
โ”‚   โ”œโ”€โ”€ Yes: "Don't play tennis"
โ”‚   โ””โ”€โ”€ No: "Play tennis"
โ””โ”€โ”€ No: Is it windy?
    โ”œโ”€โ”€ Yes: "Don't play tennis"
    โ””โ”€โ”€ No: "Play tennis"

Decision trees are popular because humans can read and understand them - crucial in healthcare, finance, and legal AI where explainability matters.

๐Ÿค”
Think about it:

A hospital uses an AI to predict patient risk. Regulators require the AI to explain its decisions. Why might a decision tree be preferred over a deep neural network here, even if the neural network is slightly more accurate?

Random Forests

A random forest builds hundreds of decision trees, each trained on a slightly different subset of the data, then takes a vote. This ensemble approach is more accurate and robust than a single tree - and it's still one of the most widely used AI techniques in industry.

How AI Uses Graphs

Knowledge Graphs

A knowledge graph stores facts as relationships between entities:

(London) --[capital_of]--> (United Kingdom)
(London) --[located_in]--> (England)
(Big Ben) --[located_in]--> (London)

Google's Knowledge Graph powers those information panels you see in search results. When you search "Big Ben," the graph connects it to London, the UK, and related landmarks.

Recommendation Graphs

Netflix, Spotify, and Amazon model users and items as a graph. If users A and B both liked items X and Y, and user A also liked item Z, the graph suggests Z to user B. This is collaborative filtering powered by graph structure.

๐Ÿง Quick Check

Why are graphs better than simple lists for modelling social networks?

Traversal - Walking Through Trees and Graphs

Depth-First Search (DFS)

DFS explores as far as possible along one path before backtracking. Think of it as exploring a maze by always taking the leftmost turn until you hit a dead end, then backtracking.

        A
       / \
      B   C
     / \   \
    D   E   F

DFS order: A โ†’ B โ†’ D โ†’ E โ†’ C โ†’ F

DFS uses a stack (naturally via recursion, or explicitly). It's great for:

  • Solving mazes and puzzles
  • Detecting cycles in graphs
  • Topological sorting (ordering tasks with dependencies)

Breadth-First Search (BFS)

BFS explores all neighbours at the current depth before moving deeper. Think of it as ripples spreading outward from a stone dropped in a pond.

        A
       / \
      B   C
     / \   \
    D   E   F

BFS order: A โ†’ B โ†’ C โ†’ D โ†’ E โ†’ F

BFS uses a queue. It's great for:

  • Finding the shortest path in an unweighted graph
  • Social network analysis (degrees of separation)
  • Web crawling (visiting pages level by level)
๐Ÿ’ก

Notice how stacks and queues from the previous lesson connect to tree and graph traversal? DFS uses a stack; BFS uses a queue. Data structures build upon each other - that's why learning them in order matters.

๐Ÿง Quick Check

You want to find the shortest route between two cities on a map where all roads are the same length. Which traversal should you use?

๐Ÿค”
Think about it:

Social media platforms measure "degrees of separation" - how many friend-of-friend hops connect two people. Which traversal algorithm would efficiently find the fewest hops between two users? How does this relate to the "six degrees of separation" idea?

๐Ÿคฏ

Google's PageRank algorithm - the original breakthrough that made Google dominant - models the web as a graph. Each web page is a node, each hyperlink is a directed edge, and a page's importance is determined by how many important pages link to it. It's essentially a random walk on a graph.

Key Takeaways

  • Trees model hierarchical data - file systems, HTML, and AI decision trees all use tree structures.
  • Binary search trees enable O(log n) lookups by maintaining a sorted hierarchy.
  • Graphs model interconnected data - social networks, knowledge bases, and recommendation engines.
  • DFS (stack-based) goes deep; BFS (queue-based) goes wide - both power core AI algorithms like PageRank and recommendation engines.