Chapter 13

Abstract Data Structures

13.0 Intro · 13.1 ADT Basics · 13.2 Stacks & Queues · 13.3 Trees & Graphs

← → or Space to navigate · F for fullscreen

13.1 ADT Basics

Interface vs. implementation · operation tradeoffs

What is an Abstract Data Type?

An ADT defines what operations a data structure supports — not how it is implemented.

Layer Concern
Interface Operations and their behavior
Implementation How operations are carried out

The interface is the contract. Users of an ADT only need to know the interface.

# Interface — what a Stack does:
# push(item)     add to top
# pop()          remove from top
# peek()         view top without removing
# is_empty()     True if no items

# Implementation A — using a Python list
class Stack:
    def __init__(self):
        self._data = []

    def push(self, item):
        self._data.append(item)

    def pop(self):
        return self._data.pop()

    def peek(self):
        return self._data[-1]

    def is_empty(self):
        return len(self._data) == 0

Operation Tradeoffs

Operation list set dict deque
Access by index O(1) — — O(1) ends, O(n) middle
Look up by key — — O(1) avg —
Search for value O(n) O(1) avg O(n) O(n)
Insert / add O(1) amortized (back) O(1) avg O(1) avg O(1) (either end)
Insert at front O(n) — — O(1)
Delete by value O(n) O(1) avg O(n) O(n)
Dominant need Best choice
Ordered history, access by position list
Fast membership or deduplication set
Key-value lookup dict
Add or remove from both ends deque
Hierarchical containment tree
Many-to-many relationships graph

BST lookup costs O(h): O(log n) when balanced, O(n) when sorted inserts build a chain.

13.2 Stacks & Queues

LIFO · FIFO · collections.deque

Stack — LIFO

Last In, First Out — like a stack of plates.

Use cases:

  • Function call stack
  • Undo/redo history
  • Balanced parentheses checking
  • Depth-first search
stack = []
stack.append("a")   # push
stack.append("b")
stack.append("c")
print(stack.pop())  # c  (last in, first out)
print(stack.pop())  # b

Balanced parentheses

def is_balanced(s):
    stack = []
    pairs = {")": "(", "]": "[", "}": "{"}
    for ch in s:
        if ch in "([{":
            stack.append(ch)
        elif ch in ")]}":
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
    return len(stack) == 0

print(is_balanced("({[]})"))   # True
print(is_balanced("({[})"))    # False

Queue — FIFO

First In, First Out — like a line at a checkout.

Use cases:

  • Task scheduling
  • BFS graph traversal
  • Print queues
  • Message queues
from collections import deque

queue = deque()
queue.append("task1")     # enqueue
queue.append("task2")
queue.append("task3")

print(queue.popleft())    # task1  (FIFO)
print(queue.popleft())    # task2

# deque is O(1) at both ends
# list.pop(0) is O(n) — avoid for queues

Stack or Queue?

Problem Better structure Reason
Undo edits Stack Undo the newest action first
Print jobs Queue Print the oldest waiting job first
Browser back button Stack Return to the most recent page
Help desk tickets Queue Serve earlier requests first
Depth-first search Stack Explore one path deeply before backing up
Breadth-first search Queue Explore nearby nodes first

13.3 Trees & Graphs

Terminology · traversals · DFS & BFS

Trees

Key terms:

  • Root: top node (no parent)
  • Children: nodes directly below a node
  • Leaf: node with no children

Use cases: folders, org charts, HTML documents, decision trees, expression trees

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.children = []

    def add_child(self, child):
        self.children.append(child)

def print_tree(node, level=0):
    print("  " * level + str(node.value))
    for child in node.children:
        print_tree(child, level + 1)

root = TreeNode("company")
analytics = TreeNode("analytics")
root.add_child(analytics)
analytics.add_child(TreeNode("alice"))
print_tree(root)
# company
#   analytics
#     alice

Binary Trees & Traversals

At most two children: left and right.

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

tree = Node(1,
            Node(2, Node(4), Node(5)),
            Node(3, None, Node(6)))
        1
      /   \
     2     3
    / \     \
   4   5     6

Height = levels on the longest root-to-leaf path (here 3).

def preorder(node):
    if node is None:
        return []
    return [node.value] + preorder(node.left) + preorder(node.right)

# inorder:   left + [node] + right
# postorder: left + right + [node]

print(preorder(tree))    # [1, 2, 4, 5, 3, 6]
print(inorder(tree))     # [4, 2, 5, 1, 3, 6]
print(postorder(tree))   # [4, 5, 2, 6, 3, 1]
Order Visit Useful for
Preorder node, left, right copy / serialize
Inorder left, node, right sorted output from a BST
Postorder left, right, node delete / evaluate children first

Binary Search Trees

Rule: left subtree < node < right subtree

def insert(root, value):
    if root is None:
        return Node(value)
    if value < root.value:
        root.left = insert(root.left, value)
    elif value > root.value:
        root.right = insert(root.right, value)
    return root

def contains(root, value):
    node = root
    while node is not None:
        if value == node.value:
            return True
        node = node.left if value < node.value else node.right
    return False
bst = None
for num in [50, 30, 70, 20, 40, 60, 80]:
    bst = insert(bst, num)

print(contains(bst, 60))   # True
print(inorder(bst))        # [20, 30, 40, 50, 60, 70, 80]

chain = None
for num in [20, 30, 40, 50, 60]:
    chain = insert(chain, num)   # every value goes right

Lookup costs O(h). Balanced (bst, h = 3): about log n. Sorted inserts build a degenerate chain (chain, h = n): O(n), no better than a list scan.

Nodes (vertices) connected by edges.

Adjacency list: each node maps to its neighbors. A two-way friendship is stored in both lists.

graph = {
    "alice": ["bob", "charlie"],
    "bob": ["alice", "dana"],
    "charlie": ["alice", "dana"],
    "dana": ["bob", "charlie"],
}
from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    visited.add(start)
    while queue:
        node = queue.popleft()
        print(node, end=" ")
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)

bfs(graph, "alice")   # alice bob charlie dana

BFS uses a queue: nearest nodes first. DFS uses a stack or recursion: one path as far as it goes, then back up. The visited set stops dana from being recorded twice.

Chapter 13 — Quick Reference

Concept Key syntax / notes
ADT Interface (what) vs. implementation (how)
Stack LIFO; list.append() / .pop()
Queue FIFO; deque.append() / .popleft()
deque O(1) at both ends; from collections import deque
Tree traversal Pre/in/post-order — recursive with base case None
BST property Left subtree < node < right subtree
BFS Queue-based; nearest nodes first
DFS Stack or recursion-based; one path at a time

End of Chapter 13

Next: Chapter 14 — Algorithms

Big O · searching · sorting · benchmarking