Sub topic 1
What a Tree Is: Nodes and Edges
Prerequisites
This chapter assumes you can write functions in a language such as Python and that you have seen recursion. You should be comfortable with objects that hold references to other objects, and with lists and dictionaries. Nothing else is required.
The working model
A tree is a data structure made of nodes joined by edges. A node is one item in the tree and holds a value. An edge is a link between two nodes. In code, an edge is usually a reference from one node to another.
Three rules make a collection of nodes and edges a tree:
- It is connected. You can get from any node to any other node by following edges.
- It has no cycles. You can never leave a node, follow edges, and return to it without retracing a step.
- It has one designated starting node, the root, when we treat the tree as rooted. Every other node hangs below the root.
These rules fix the number of edges. A tree with n nodes always has exactly n - 1 edges. Adding one more edge would create a cycle. Removing one would disconnect the tree.
Lists, files in folders, and HTML documents all have this shape. A folder holds files and other folders, and those folders hold more items.
A tree in code
The smallest useful tree class stores a value and a list of children. Each entry in that list is an edge pointing down to another node.
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children or []
def is_leaf(self):
return not self.children
# A is the root. Leaves are C, E, F, and G.
tree = Node("A", [
Node("B", [Node("E"), Node("F")]),
Node("C"),
Node("D", [Node("G")]),
])This tree has 7 nodes (A, B, C, D, E, F, G) and 6 edges: A to B, A to C, A to D, B to E, B to F, and D to G. That matches n - 1.
The edges here point only downward. A node knows its children but not its parent. The root is the one node that no other node points to. This is how code finds the root: it is the node you keep a variable for.
Common errors
- Creating a cycle. If you add a node to its own descendant's children list, a traversal never ends. Recursive functions then fail with a stack overflow.
- Sharing a node between two parents. Reusing one
Nodeobject in two children lists makes the structure a graph, not a tree. Counts and measurements of the tree will then be wrong. - Forgetting the default argument pitfall. Writing
children=[]in the constructor shares one list across all nodes. Thechildren or []pattern avoids this.
Exercise
Exercise
A tree has 10 nodes. How many edges does it have, and why can't it have 10?
Show answer
It has 9 edges (n - 1). With 10 edges, some pair of nodes would be joined by a second route, which forms a cycle, so the structure would no longer be a tree.