Modeling Hierarchies and Relationships¶

Trees and graphs extend node thinking from chains into branching relationships¶
Linked lists connected one node to the next in a line. Trees and graphs widen that idea: a node can connect to multiple other nodes, which lets you model hierarchies, routes, dependencies, recommendations, and many other relationship patterns.
Core Explanation¶
A tree is a special kind of graph with parent-child structure and no cycles.
A graph is more general and may represent many types of connections.
Continuity from linked structures
Linked lists gave each node one or two direct neighbors. Trees and graphs remove that restriction, so one node can branch to several others.
tree = {
"A": ["B", "C"],
"B": [],
"C": ["D"],
"D": []
}
print(tree["A"])Worked Example: hierarchy versus network¶
The code cell above shows a tree-like structure: one node can have children, and the relationships form a clear hierarchy. That is different from a general graph, where nodes may connect in more flexible patterns such as routes, collaboration networks, or recommendation links.
Exercises¶
Describe one example of a hierarchy and one example of a network.
Explain why every tree is a graph, but not every graph is a tree.
Draw a tiny tree with a root and two children.
Give one example where a graph is a better model than a tree.
Hint
If the structure has one top level and clear parent-child levels, think tree. If connections can cross freely between many nodes, think graph.
Quick Summary
trees model hierarchy
graphs model relationships more generally
trees are a special case of graphs
these structures support many important algorithms
Practice Lab¶
Expected output
['Ops', 'Sales']
['Warehouse']This first example behaves like a tree: the top node branches into departments, and lower nodes continue the hierarchy.
Expected output
['B', 'C']
4This second example behaves like a graph: node D can be reached from more than one parent path, which already feels less tree-like and more network-oriented.
Reading Node Relationships¶
These short examples separate hierarchy thinking from general connectivity.
Read children in a tree¶
A tree node often points to the next level of the hierarchy.
Count nodes in a graph¶
An adjacency-list dictionary can show how many nodes are currently defined.
Check shared connections¶
Graphs often highlight that multiple nodes can connect to the same destination.
Guided Practice¶
What is a key difference between a tree and a general graph?¶
In the graph example, how many nodes are defined?¶
Key Takeaway¶
Trees and graphs both organize data through nodes and connections, but trees emphasize hierarchy while graphs emphasize general relationships. This overview prepares you for the next tree-specific notebooks on traversal and binary search trees.