Modeling General Relationships¶
graph = {
"A": ["B", "C", "D"],
"B": ["E", "F"],
"C": ["G"],
"D": ["H"],
"E": [],
"F": [],
"G": [],
"H": [],
}
print(graph["A"])
print(graph["B"])
Graphs model networks where connections are more flexible than a tree¶
Binary search trees relied on strict ordering and parent-child structure. Graphs relax those rules: a node can connect to many others in patterns that look more like routes, dependencies, recommendations, or social links than a simple hierarchy.
Core Explanation¶
Graphs represent entities and the connections between them.
They are useful for transportation networks, dependency graphs, recommendation systems, and social relationships.
How to read this figure
Ais a starting node with three direct neighborsB,C, andDare branch points reached in one stepE,F,G, andHare outer nodes reached after following a branch
This same graph shape is reused in the BFS and DFS notebooks so the traversal order is easier to compare visually.
Continuity from binary search trees
BSTs used structure to narrow search by ordering. Graphs drop that left/right ordering and instead focus on which nodes are connected at all.
Worked Example and Practice Lab¶
Expected output
['B', 'C', 'D']
['E', 'F']This example uses an adjacency list: each node maps to the nodes it can reach directly.
Expected output
3
TrueReading Graph Connectivity¶
These short examples focus on how adjacency lists describe a network.
Read outgoing neighbors¶
A node’s adjacency list shows where it can connect next.
Count outgoing edges¶
You can count how many direct connections a node has.
Check whether a node exists¶
Graph dictionaries also let you test whether a node is present in the structure.
Exercises¶
Explain what a node and an edge represent in a graph.
Describe one real-world system that is better modeled as a graph than as a tree.
Explain what the adjacency list for node
Ameans in the example.Give one reason graphs are a natural setup for BFS or DFS.
Hint
A graph is often the right model when one item can connect to several others without a strict hierarchy.
Guided Practice¶
What does an adjacency list represent in a graph?¶
How many outgoing neighbors does node `A` have in the example?¶
Key Takeaway¶
Graphs describe general connectivity rather than strict hierarchy or ordered branching. That foundation prepares you for BFS and DFS, where the central question becomes how to explore a network systematically.