Home β€Ί Curriculum β€Ί Trees & Graphs
Updated for Python 3.12+ Β· November 2026

🌳 Trees & Graphs
in Python

Learn trees and graphs in Python: nodes, binary search trees, traversals, adjacency lists, BFS, DFS, shortest paths, cycle detection and Dijkstra with heapq.

Advanced 9 lessonsβ‰ˆ 50 min read by Glenn Pansensoy

What this lesson is about

Trees and graphs are the data structures you reach for when your data is about relationships instead of a simple sequence. A folder on your disk contains folders, a web page contains elements, a company has managers and reports, a map has towns joined by roads, a social network has people joined by friendships. None of these fit comfortably into a flat list, but all of them fit naturally into a tree or a graph.

A tree is a connected structure with one root and no loops: every node has one parent (except the root) and any number of children. A graph is the general case: nodes joined by edges, possibly with loops, possibly with directions and weights. Trees are really just graphs with extra rules, so the skills transfer. Once you can walk a tree and walk a graph, you can solve a huge family of problems: finding routes, ordering tasks, detecting circular dependencies and searching ordered data quickly.

In this lesson I build everything from scratch with plain classes, dictionaries, lists and the standard library, and every example runs in your browser. We start with tree nodes and the binary search tree, then the four classic traversals, then move to graphs stored as adjacency lists, breadth-first and depth-first search, shortest paths, cycle detection and finally Dijkstra's algorithm using heapq. I print the visit order at each step so you can watch the algorithms work. If recursion still feels shaky, skim recursion first, and keep Big-O nearby for the complexity notes.

What you will learn

  • βœ“Model a tree with a small Node class and measure its height and size
  • βœ“Insert into and search a binary search tree, and see why order makes search fast
  • βœ“Write inorder, preorder, postorder and level-order traversals
  • βœ“Store a graph as an adjacency list using a dictionary of lists
  • βœ“Explore a graph with breadth-first search and depth-first search
  • βœ“Find shortest paths in an unweighted graph and rebuild the actual route
  • βœ“Detect cycles in undirected and directed graphs
  • βœ“Use heapq to implement Dijkstra's algorithm for weighted graphs

Why programmers should learn this

  • β˜…Anything hierarchical, such as file systems, HTML documents, JSON, organisation charts and menus, is a tree, so tree thinking helps you read and process real data.
  • β˜…Routing, recommendations, dependency resolution and social features are graph problems; the same BFS and DFS patterns underlie package managers, build tools and map applications.
  • β˜…Binary search trees show how keeping data ordered makes lookup fast, which is the idea behind database indexes and sorted containers.
  • β˜…Trees and graphs are among the most common topics in technical interviews, and the patterns (traverse, track visited, use a queue or stack) repeat constantly.
  • β˜…Working with them strengthens recursion, queues, stacks and hash maps, so the lesson improves your general problem-solving, not just one topic.

Trees and nodes

A tree is built from nodes. Each node stores a value and references to its children. The topmost node is the root, a node with no children is a leaf, and the number of edges on the longest path from the root down to a leaf is the tree's height. Because a node's children are themselves nodes with their own children, a tree is a recursive structure, and recursive functions are the natural way to process it.

In a binary tree each node has at most two children, called left and right. That small restriction is enough to build some of the most useful structures in computing. In Python a node is just a tiny class with three attributes. A missing child is represented by None.

Below I build a small tree by hand and write two recursive functions. The size of a tree is one (for the node itself) plus the size of the left subtree plus the size of the right subtree; the height follows the same pattern using max. Notice the base case: an empty tree, None, has size 0 and height -1 (or 0 if you count nodes rather than edges). Every tree function starts with that question.

python
class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def size(node):
    if node is None:
        return 0
    return 1 + size(node.left) + size(node.right)

def height(node):
    if node is None:
        return -1
    return 1 + max(height(node.left), height(node.right))

#        10
#       /  \
#      5    15
#     / \     \
#    2   7     20
root = Node(10)
root.left = Node(5)
root.right = Node(15)
root.left.left = Node(2)
root.left.right = Node(7)
root.right.right = Node(20)

print("size  :", size(root))
print("height:", height(root))
print("root children:", root.left.value, root.right.value)
print("leaf has children?", root.left.left.left, root.left.left.right)
Expected output
size  : 6
height: 2
root children: 5 15
leaf has children? None None

Line by line

  1. 1-5A node stores a value plus links to a left and a right child. Both start as None, meaning no child.
  2. 7-10size counts nodes. The base case is an empty tree (None) which has 0 nodes; otherwise count this node plus both subtrees.
  3. 12-15height uses the same shape. An empty tree is -1, so a single node has height 0, and each level adds one.
  4. 17-22A comment sketch of the tree we are about to build, which helps you picture the links.
  5. 23-28Create the nodes and attach them by assigning to left and right.
  6. 30-33Print size, height and a couple of links. A leaf's children are both None.
ℹ️

Each function visits every node once, so size and height both take O(n) time. The recursion depth equals the height of the tree, which matters for very lopsided trees.

Binary search trees: insert and search

A binary search tree (BST) adds one rule to a binary tree: for every node, everything in its left subtree is smaller and everything in its right subtree is larger. That rule is what makes searching fast. At each node you compare the target with the node's value and throw away half of the remaining tree, in the same spirit as binary search on a sorted list.

To insert, you walk down exactly as you would to search: go left when the new value is smaller, right when larger, and when you reach an empty spot you attach a new node there. I have written both operations iteratively with a loop, which avoids recursion limits and shows the walk clearly. The code also records the path it takes so you can see the comparisons.

On a reasonably balanced tree with n nodes the height is about log n, so insert and search take O(log n) time. The word *reasonably* is important, and I return to it in a later section: if you insert already sorted data the tree degenerates into a chain and every operation becomes O(n).

python
class Node:
    def __init__(self, value):
        self.value, self.left, self.right = value, None, None

def insert(root, value):
    if root is None:
        return Node(value)
    cur = root
    while True:
        if value < cur.value:
            if cur.left is None:
                cur.left = Node(value)
                break
            cur = cur.left
        elif value > cur.value:
            if cur.right is None:
                cur.right = Node(value)
                break
            cur = cur.right
        else:
            break          # ignore duplicates
    return root

def search(root, target):
    path = []
    cur = root
    while cur is not None:
        path.append(cur.value)
        if target == cur.value:
            return True, path
        cur = cur.left if target < cur.value else cur.right
    return False, path

root = None
for v in [50, 30, 70, 20, 40, 60, 80, 35]:
    root = insert(root, v)

print(search(root, 35))
print(search(root, 65))
print(search(root, 50))
Expected output
(True, [50, 30, 40, 35])
(False, [50, 70, 60])
(True, [50])

Line by line

  1. 1-3A node class again; the three attributes are assigned in one tuple statement.
  2. 5-7Inserting into an empty tree simply creates the root.
  3. 8-21Walk down from the root. Smaller values go left, larger go right, and when the chosen child slot is empty we place the new node there and stop. Equal values are ignored so the tree holds unique keys.
  4. 22Return the root so callers can write root = insert(root, v) even when the tree was empty.
  5. 24-32search follows the same walk and records each value it compares against. It returns whether the target was found plus the path taken.
  6. 34-36Build the tree from eight values. Because the first value is 50, 50 becomes the root.
  7. 38-40Search for a present value, a missing value and the root. The path length is the number of comparisons.

Look at the paths in the output. Finding 35 takes four comparisons even though the tree holds eight values. Each comparison discards a whole subtree. Finding 65 fails after landing on an empty slot below 60, and that is exactly where an insert of 65 would go. That is the key insight: search and insert are the same walk.

Tree traversals: four ways to visit every node

A traversal visits every node exactly once. The order matters. Inorder (left, node, right) visits a BST in sorted order, which is a neat property and a useful way to check that a tree really is a BST. Preorder (node, left, right) visits a parent before its children, which is how you would copy a tree or print a folder structure. Postorder (left, right, node) visits children first, which suits deleting a tree or computing sizes of folders from the bottom up.

The first three are depth-first: they dive down one branch before coming back. Level-order (also called breadth-first) visits the tree one row at a time from the top, using a queue instead of recursion. I use collections.deque because removing from the front of a plain list is O(n) while popleft() on a deque is O(1). See stacks and queues for more on that.

All four run in O(n) time because each node is processed once. The recursive ones use O(h) extra space for the call stack, where h is the height, and level-order uses space proportional to the widest level. I have written each traversal to return a list, which makes the results easy to print and compare.

python
from collections import deque

class Node:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right

def inorder(n):
    return inorder(n.left) + [n.value] + inorder(n.right) if n else []

def preorder(n):
    return [n.value] + preorder(n.left) + preorder(n.right) if n else []

def postorder(n):
    return postorder(n.left) + postorder(n.right) + [n.value] if n else []

def level_order(root):
    out, queue = [], deque([root])
    while queue:
        node = queue.popleft()
        out.append(node.value)
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)
    return out

tree = Node(8,
        Node(3, Node(1), Node(6, Node(4), Node(7))),
        Node(10, None, Node(14, Node(13))))

print("inorder   :", inorder(tree))
print("preorder  :", preorder(tree))
print("postorder :", postorder(tree))
print("level     :", level_order(tree))
Expected output
inorder   : [1, 3, 4, 6, 7, 8, 10, 13, 14]
preorder  : [8, 3, 1, 6, 4, 7, 10, 14, 13]
postorder : [1, 4, 7, 6, 3, 13, 14, 10, 8]
level     : [8, 3, 10, 1, 6, 14, 4, 7, 13]

Line by line

  1. 1deque gives us a fast queue for the level-order version.
  2. 3-5A node whose children can be passed to the constructor, so a whole tree can be written as one nested expression.
  3. 7-8Inorder: everything on the left, then this node, then everything on the right. The conditional expression returns an empty list for None.
  4. 10-14Preorder puts the node first; postorder puts it last. Only the position of [n.value] changes.
  5. 16-25Level-order starts with the root in a queue. Take a node from the front, record it, then add its children to the back, so shallower nodes are always handled first.
  6. 27-29Build the tree in a single nested expression.
  7. 31-34Print all four orders. Inorder comes out sorted because this tree happens to obey the BST rule.
πŸ’‘

To remember the names, look at where the node sits relative to its children: pre = before, in = between, post = after.

Graphs and adjacency lists

A graph is a set of vertices (nodes) and edges connecting pairs of them. Edges can be undirected (a friendship works both ways) or directed (a one-way street, or 'task A must finish before task B'). They can also carry weights, such as distance or cost. Unlike a tree, a graph can contain cycles and can be disconnected into separate islands.

The most common Python representation is an adjacency list: a dictionary mapping each vertex to a list of its neighbours. It is compact for sparse graphs, where each vertex connects to only a few others, because you store only the edges that exist. The alternative, an adjacency matrix, uses a grid of size V by V and wastes space unless the graph is dense, though it can answer 'is there an edge between a and b?' in constant time.

I use defaultdict(list) so I do not have to check whether a key exists before appending. For an undirected graph every edge is stored twice, once in each direction. I sort neighbour lists before printing so the output stays deterministic and easy to follow.

python
from collections import defaultdict

edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("D", "E"), ("F", "G")]

graph = defaultdict(list)
for a, b in edges:
    graph[a].append(b)
    graph[b].append(a)          # undirected: store both directions

for vertex in sorted(graph):
    print(vertex, "->", sorted(graph[vertex]))

print("vertices:", len(graph))
print("edges   :", sum(len(n) for n in graph.values()) // 2)
print("degree of D:", len(graph["D"]))
print("B-D edge?", "D" in graph["B"])
Expected output
A -> ['B', 'C']
B -> ['A', 'D']
C -> ['A', 'D']
D -> ['B', 'C', 'E']
E -> ['D']
F -> ['G']
G -> ['F']
vertices: 7
edges   : 6
degree of D: 3
B-D edge? True

Line by line

  1. 1defaultdict(list) creates an empty list the first time a key is used.
  2. 3The edge list. Note that F and G are connected to each other but not to the rest, so this graph has two components.
  3. 5-8Build the adjacency list. Each undirected edge is added in both directions.
  4. 10-11Print every vertex with its sorted neighbours.
  5. 13-16The vertex count, the edge count (each edge was stored twice, so divide by two), the degree of D (number of neighbours) and an edge membership test.

Space for an adjacency list is O(V + E), where V is the number of vertices and E the number of edges. Looking up whether a specific edge exists costs O(degree) with lists, or O(1) if you store neighbours in a set instead. Choose the representation to match the questions you will ask.

Breadth-first and depth-first search

Searching a graph means visiting vertices by following edges. Because graphs can have cycles, you must remember which vertices you have already visited or you will loop forever. A set is perfect for that.

Breadth-first search (BFS) explores in rings: first the start vertex, then all its neighbours, then all their unvisited neighbours, and so on. It uses a queue. Depth-first search (DFS) follows one path as far as it can before backing up, which you can write with recursion or an explicit stack. Both visit every reachable vertex once and every edge once or twice, so both run in O(V + E) time.

Which should you use? BFS is the tool when the number of edges from the start matters, because the first time it reaches a vertex is by a shortest path (in terms of edge count). DFS is a better fit when you need to explore every possibility down a branch, check connectivity, find components, or order tasks. The code below runs both on the same graph and prints the visit order. I visit neighbours in alphabetical order to keep results predictable.

python
from collections import deque

graph = {
    "A": ["B", "C"],
    "B": ["A", "D", "E"],
    "C": ["A", "F"],
    "D": ["B"],
    "E": ["B", "F"],
    "F": ["C", "E"],
}

def bfs(start):
    seen = {start}
    queue = deque([start])
    order = []
    while queue:
        v = queue.popleft()
        order.append(v)
        for nb in sorted(graph[v]):
            if nb not in seen:
                seen.add(nb)
                queue.append(nb)
    return order

def dfs_recursive(v, seen=None, order=None):
    if seen is None:
        seen, order = set(), []
    seen.add(v)
    order.append(v)
    for nb in sorted(graph[v]):
        if nb not in seen:
            dfs_recursive(nb, seen, order)
    return order

def dfs_iterative(start):
    seen, order, stack = set(), [], [start]
    while stack:
        v = stack.pop()
        if v in seen:
            continue
        seen.add(v)
        order.append(v)
        for nb in sorted(graph[v], reverse=True):
            if nb not in seen:
                stack.append(nb)
    return order

print("BFS          :", bfs("A"))
print("DFS recursive:", dfs_recursive("A"))
print("DFS iterative:", dfs_iterative("A"))
Expected output
BFS          : ['A', 'B', 'C', 'D', 'E', 'F']
DFS recursive: ['A', 'B', 'D', 'E', 'F', 'C']
DFS iterative: ['A', 'B', 'D', 'E', 'F', 'C']

Line by line

  1. 3-10The graph as a plain dictionary of neighbour lists. It forms a cycle A-B-E-F-C-A with a branch to D.
  2. 12-23BFS marks a vertex as seen when it is *added* to the queue, not when it is removed. That prevents the same vertex from being queued twice.
  3. 25-33Recursive DFS. The first call creates the seen set and order list; the recursive calls share them.
  4. 35-45Iterative DFS replaces the call stack with our own list. We push neighbours in reverse sorted order so that the smallest neighbour is popped first, which makes the order match the recursive version.
  5. 47-49Print each visit order. BFS goes B, C then D, E, F by level; DFS dives A, B, D, E, F, C.
⚠️

Marking a vertex visited at the wrong moment is a classic bug. In BFS, mark it when you enqueue it; otherwise a vertex can enter the queue many times and the algorithm slows down or misbehaves.

Shortest paths in an unweighted graph

When every edge counts as one step, BFS finds the shortest path for free. Because BFS visits vertices in order of their distance from the start, the first time we reach a vertex we have reached it by the fewest possible edges. To recover the actual route rather than only its length, we record for each vertex which vertex we came from, a dictionary usually called parent or prev.

After the search finishes, we start at the destination and follow the parent links backwards until we reach the start, then reverse the list. If the destination never appears in parent, there is no path at all, which is itself useful information: it tells you the two vertices lie in different components.

The example is a tiny grid of rooms. I also print the distance table, which is a common by-product. Time is O(V + E) and the extra space is O(V) for the parent and distance records.

python
from collections import deque

graph = {
    "Gate": ["Hall", "Yard"],
    "Hall": ["Gate", "Library", "Kitchen"],
    "Yard": ["Gate", "Kitchen"],
    "Library": ["Hall", "Tower"],
    "Kitchen": ["Hall", "Yard", "Tower"],
    "Tower": ["Library", "Kitchen"],
    "Island": [],
}

def shortest_path(start, goal):
    parent = {start: None}
    dist = {start: 0}
    queue = deque([start])
    while queue:
        v = queue.popleft()
        if v == goal:
            break
        for nb in graph[v]:
            if nb not in parent:
                parent[nb] = v
                dist[nb] = dist[v] + 1
                queue.append(nb)
    if goal not in parent:
        return None, dist
    path = []
    while goal is not None:
        path.append(goal)
        goal = parent[goal]
    return path[::-1], dist

path, dist = shortest_path("Gate", "Tower")
print("path:", " -> ".join(path))
print("steps:", len(path) - 1)
print("distances:", dict(sorted(dist.items())))
print("to Island:", shortest_path("Gate", "Island")[0])
Expected output
path: Gate -> Hall -> Library -> Tower
steps: 3
distances: {'Gate': 0, 'Hall': 1, 'Kitchen': 2, 'Library': 2, 'Tower': 3, 'Yard': 1}
to Island: None

Line by line

  1. 3-11A graph of rooms. Island has no neighbours, so it cannot be reached from anywhere.
  2. 13-26BFS from the start. parent doubles as the visited set: a vertex is known once it has a parent entry. dist stores the number of edges from the start.
  3. 27-28If the goal never got a parent, no path exists, so we return None.
  4. 29-33Walk backwards from the goal using parent until reaching the start (whose parent is None), then reverse to get start-to-goal order.
  5. 35-38Print the route, the step count, the distance table so far and the unreachable case.
ℹ️

The early break stops the search as soon as the goal is dequeued, so the distance table only covers vertices discovered up to that point. Remove the break if you want distances to everything.

Cycle detection

A cycle is a path that starts and ends at the same vertex. Detecting cycles matters in practice: a cycle in a task dependency graph means the tasks can never be ordered, a cycle in an import graph means a circular import, and a cycle in a 'must finish before' graph is a deadlock.

In an undirected graph, run DFS and remember the vertex you arrived from. If you meet an already visited vertex that is not your immediate parent, you have found a cycle. The parent exception matters because every undirected edge can be walked in both directions, and walking straight back is not a real loop.

In a directed graph the rule is different. A vertex reached twice is not necessarily a cycle: two different paths can lead to the same place (a diamond shape). A cycle exists only when DFS reaches a vertex that is still on the current path. So we track three states: unvisited, in progress (on the current recursion stack) and done. Meeting an in-progress vertex means we looped back. The code tests both kinds.

python
def has_cycle_undirected(graph):
    seen = set()
    def dfs(v, parent):
        seen.add(v)
        for nb in graph[v]:
            if nb == parent:
                continue
            if nb in seen or dfs(nb, v):
                return True
        return False
    return any(dfs(v, None) for v in graph if v not in seen)

def has_cycle_directed(graph):
    WHITE, GREY, BLACK = 0, 1, 2
    state = {v: WHITE for v in graph}
    def dfs(v):
        state[v] = GREY
        for nb in graph[v]:
            if state[nb] == GREY:
                return True
            if state[nb] == WHITE and dfs(nb):
                return True
        state[v] = BLACK
        return False
    return any(state[v] == WHITE and dfs(v) for v in graph)

tree_like = {1: [2, 3], 2: [1], 3: [1]}
triangle  = {1: [2, 3], 2: [1, 3], 3: [1, 2]}
print("undirected tree    :", has_cycle_undirected(tree_like))
print("undirected triangle:", has_cycle_undirected(triangle))

diamond = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
loop    = {"a": ["b"], "b": ["c"], "c": ["a"]}
print("directed diamond   :", has_cycle_directed(diamond))
print("directed loop      :", has_cycle_directed(loop))
Expected output
undirected tree    : False
undirected triangle: True
directed diamond   : False
directed loop      : True

Line by line

  1. 1-11Undirected check. dfs(v, parent) skips the vertex we came from. Meeting any other seen vertex proves a cycle. any(...) starts a fresh DFS for each unvisited component.
  2. 13-26Directed check with three states, named WHITE (not seen), GREY (on the current path) and BLACK (completely finished).
  3. 16-24Entering a vertex marks it GREY. A GREY neighbour means we have found a way back to an ancestor, which is a cycle. When all neighbours are handled the vertex turns BLACK.
  4. 28-31Two undirected examples: a tree-shaped graph has no cycle, a triangle has one.
  5. 33-36The diamond reaches d twice but has no cycle, while the three-vertex loop does.

Both checks run in O(V + E). The directed version is the first half of topological sorting: if no cycle exists, you can order the vertices so that every edge points forward, which is how build tools decide what to compile first.

Weighted graphs and Dijkstra with heapq

When edges have different costs, fewest edges no longer means cheapest route. A road with three short hops can beat a single long road. Dijkstra's algorithm solves single-source shortest paths when all weights are non-negative. The idea is greedy: always finalise the unvisited vertex with the smallest known distance, then see whether going through it improves any neighbour.

To pick the smallest distance quickly we use a priority queue. Python's heapq module provides a min-heap on a plain list: heappush adds an item and heappop removes the smallest in O(log n). We push tuples of (distance, vertex) so the smallest distance comes out first. A vertex can be pushed several times with different distances; when we pop an entry that is worse than what we already know, we skip it. This is called lazy deletion and it is simpler than updating items inside the heap.

With a binary heap, Dijkstra runs in O((V + E) log V). It does not work with negative edge weights, because a later negative edge could undo a decision the algorithm already treated as final. For those graphs you need Bellman-Ford. The example prints each step of the search so you can follow the frontier.

python
import heapq

graph = {
    "A": [("B", 4), ("C", 1)],
    "B": [("D", 1)],
    "C": [("B", 2), ("D", 5)],
    "D": [("E", 3)],
    "E": [],
}

def dijkstra(start):
    dist = {v: float("inf") for v in graph}
    dist[start] = 0
    prev = {}
    heap = [(0, start)]
    while heap:
        d, v = heapq.heappop(heap)
        if d > dist[v]:
            continue                      # stale entry
        print(f"settle {v} at {d}")
        for nb, w in graph[v]:
            nd = d + w
            if nd < dist[nb]:
                dist[nb] = nd
                prev[nb] = v
                heapq.heappush(heap, (nd, nb))
    return dist, prev

dist, prev = dijkstra("A")
print(dist)

route, v = [], "E"
while v in prev or v == "A":
    route.append(v)
    if v == "A":
        break
    v = prev[v]
print("route A->E:", " -> ".join(reversed(route)), "cost", dist["E"])
Expected output
settle A at 0
settle C at 1
settle B at 3
settle D at 4
settle E at 7
{'A': 0, 'B': 3, 'C': 1, 'D': 4, 'E': 7}
route A->E: A -> C -> B -> D -> E cost 7

Line by line

  1. 3-9A directed weighted graph: each neighbour is a pair (vertex, weight). The direct edge A to B costs 4, but A to C to B costs only 3.
  2. 12-14Every distance starts at infinity except the start, which is 0. prev will remember the best predecessor of each vertex.
  3. 15-17The heap holds (distance, vertex) pairs; popping always gives the closest unsettled candidate.
  4. 18-19If the popped distance is larger than the recorded one, a better route was already found, so skip this stale entry.
  5. 20-26Settle the vertex, then try to relax each outgoing edge: if going through this vertex is cheaper, update the distance and predecessor and push the new candidate.
  6. 31-32Run it and print the final distance table.
  7. 34-40Rebuild the route by following prev backwards from E to A, then reverse it.
⚠️

Dijkstra assumes no negative edge weights. If your data can have negative costs, this algorithm can return wrong answers without any error message.

Balance, complexity and choosing the right structure

Everything I claimed about BST speed depends on the shape of the tree. If you insert 1, 2, 3, 4, 5 in order into a plain BST, each value goes to the right of the previous one and you get a linked list in disguise, with height n - 1. Search then degrades from O(log n) to O(n). Self-balancing trees such as AVL and red-black trees rotate nodes during insertion to keep the height close to log n. In Python you rarely write one yourself: the bisect module on a sorted list, a dict, a set or a heap usually does the job, and for heavy ordered-container work a library such as sortedcontainers is a common choice.

Let me show the difference with a measurement that does not depend on timing: the height of a tree built from sorted input versus the same values inserted in a shuffled but fixed order. Height is the number of comparisons the worst search needs, so it is a fair stand-in for speed.

For graphs, think about density and the question you are asking. Adjacency lists give O(V + E) traversals and suit most real graphs. Use BFS for fewest hops, Dijkstra for cheapest weighted routes, DFS for components, cycles and orderings, and sets for visited tracking. Keep an eye on recursion depth in Python, which defaults to roughly a thousand frames: a long chain graph can overflow the recursive DFS, and the iterative version with an explicit stack avoids that.

python
class Node:
    def __init__(self, v):
        self.v, self.left, self.right = v, None, None

def insert(root, v):
    if root is None:
        return Node(v)
    cur = root
    while True:
        side = "left" if v < cur.v else "right"
        nxt = getattr(cur, side)
        if nxt is None:
            setattr(cur, side, Node(v))
            return root
        cur = nxt

def height(n):
    return -1 if n is None else 1 + max(height(n.left), height(n.right))

def build(values):
    root = None
    for v in values:
        root = insert(root, v)
    return root

sorted_vals = list(range(1, 32))
balanced_order = [16, 8, 24, 4, 12, 20, 28, 2, 6, 10, 14, 18, 22, 26, 30,
                  1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31]

print("31 values inserted in sorted order  : height", height(build(sorted_vals)))
print("31 values inserted in balanced order: height", height(build(balanced_order)))
Expected output
31 values inserted in sorted order  : height 30
31 values inserted in balanced order: height 4

Line by line

  1. 1-3A minimal node class.
  2. 5-15Iterative insert. getattr and setattr pick the left or right slot by name so we do not need two copies of the loop.
  3. 17-18Height with the same recursive shape as earlier.
  4. 20-24Build a tree by inserting each value in turn.
  5. 26-28The same 31 numbers in two different insertion orders. The second list starts with the middle value, then the middle of each half, and so on.
  6. 30-31Compare heights: the sorted order produces a chain of height 30, the balanced order a perfectly packed tree of height 4.

Notice that the data is identical in both cases. Only the order of insertion changed, and the cost of searching went from about 31 comparisons to 5. That gap grows with the data: for a million values a balanced tree needs around twenty comparisons while a chain could need a million.

Common mistakes

❌ Forgetting the visited set

Without tracking visited vertices, BFS or DFS on a graph with a cycle never terminates. Add vertices to a set and check it before queueing or recursing.

❌ Using a list as a queue

list.pop(0) shifts every remaining element, so BFS becomes slower than it should be. Use collections.deque and popleft().

❌ Treating a directed graph like an undirected one

In a directed graph, reaching a vertex twice is not a cycle. You need the in-progress (grey) state or a recursion stack to detect real cycles.

❌ Assuming a BST is always balanced

Inserting sorted data into a plain BST creates a chain and O(n) operations. Shuffle the input, or use a balanced structure or a library when order is not under your control.

❌ Using Dijkstra with negative weights

The algorithm finalises vertices greedily and cannot undo that when a negative edge appears later. Use Bellman-Ford if negative weights are possible.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. Which traversal of a binary search tree produces its values in sorted order?

Q2. Which structure does breadth-first search use to hold vertices still to be explored?

Q3. What is the time complexity of BFS on a graph stored as an adjacency list?

Q4. Why do we push (distance, vertex) tuples onto the heap in Dijkstra's algorithm?

Q5. What is the height of a plain BST after inserting 1, 2, 3, 4, 5 in that order?

Q6. For a directed graph, when has DFS found a cycle?

Frequently asked questions

A tree is a connected graph with no cycles, usually with a designated root. A graph is the general structure: it may have cycles, several components, directions and weights.

Use BFS when you want the fewest steps from a start vertex, for example the shortest path in an unweighted graph. Use DFS for exploring all possibilities, finding components, detecting cycles and topological ordering. Both cost O(V + E).

A matrix needs V times V cells, which is wasteful for sparse graphs and slows traversals because you scan whole rows. It is a good choice only for small or dense graphs, or when you need constant-time edge checks.

No. You build them from classes, dictionaries and lists. Libraries such as networkx provide full-featured graphs, but understanding the basic structures first makes those tools easier to use.

Python limits recursion depth, by default to about a thousand calls. For deep or chain-like graphs, write DFS with an explicit stack as shown in the lesson, or rethink the approach. See recursion for more.

Key takeaways

  • βœ“A tree is a recursive structure of nodes; most tree functions are a base case for None plus a combination of the left and right results.
  • βœ“A BST keeps smaller values left and larger right, giving O(log n) search when balanced and O(n) when degenerate.
  • βœ“Inorder, preorder and postorder are depth-first; level-order uses a queue and visits row by row.
  • βœ“Adjacency lists (a dict of lists) store graphs in O(V + E) space and suit most sparse graphs.
  • βœ“BFS finds fewest-edge paths, DFS explores deeply, and both need a visited set to survive cycles.
  • βœ“Dijkstra with a heapq priority queue handles non-negative weights in O((V + E) log V).