Data Structures II (Hierarchical & Networked)
Trees, search trees, and graphs — data structures with family relationships.
After arrays and linked lists, you might think data always sits in a line. But most real-world relationships are hierarchical (folders, org charts) or networked (roads, social connections). Trees and graphs capture these shapes — and the algorithms that traverse them power everything from web browsers to navigation apps.
This article introduces the three structures that bridge linear data and the search algorithms you will study next: trees, binary search trees, and graphs.
Trees — Hierarchy with Rules
Tree
Real file systems have symbolic links creating multiple paths to the same file, violating the tree property and turning the structure into a graph. The family-tree analogy also breaks because real people have two biological parents, while tree nodes have exactly one parent.
Example: The DOM Tree
No cycles, one root, exactly one path between any two nodes. Edges = n − 1. Strict hierarchy.
Cycles allowed, no root required, multiple paths possible. Flexible connections without fixed hierarchy.
Misconception: Trees and Graphs Are Completely Different
Binary Search Trees — Ordered for Speed
Binary Search Tree (BST)
A phone book is flat and sequential; a BST is hierarchical. Also, the logarithmic guarantee depends on balance — sorted insertion creates a "one-page phone book" (linked list). The analogy hides the balance requirement.
BST Search: Step by Step
Balance Is Everything
Misconception: BST Search Is Always O(log n)
Deep Dive: Self-Balancing Trees
Interactive: BST Search Step by Step
You learned that a BST halves the search space with each comparison. Click through the steps of a real search and observe how the algorithm traverses the tree — node by node, comparison by comparison.
The search starts at the root (50). The target value 40 is less than 50 — so the algorithm goes left.
Graphs — The General Network
Graph
Subway networks are bound by geography, Euclidean distances, and physical laws. Abstract graphs have no such constraints — a node in Tokyo can have a direct edge with cost 0 to a node in Berlin.
Graphs in the Real World
Misconception: Directed Graphs Allow Travel in Both Directions
Deep Dive: How Are Graphs Stored?
Key Takeaways
Quiz: Hierarchical Data Structures
Checkpoint: Do You Understand Hierarchical Data Structures?
- I can define a tree by its rules (root, parent, children, leaves, no cycles) and explain why every tree is a graph but not every graph is a tree.
- I can trace a search in a BST and explain when it is O(log n) versus when it degenerates to O(n).
- I can distinguish directed from undirected and weighted from unweighted graphs, and name one real-world system for each.