Sub topic 2
The root: where every tree starts
This chapter assumes you can read basic Python, including classes, lists, and sets. It also assumes you know that one object can hold references to other objects.
What the root is
The root is the one node in a tree that has no parent. Every other node is reachable by starting at the root and following edges downward. An edge is a link from a parent to one of its children.
A tree has exactly one root. If a structure has two nodes with no parent, it is two separate trees (a forest), not one tree. If a structure has no parentless node, it contains a cycle, which a tree cannot have.
In the diagram, A is the root. Nothing points to A, and every other node has exactly one arrow pointing at it.
Why the root matters
The root is the entry point. A tree object usually stores only a reference to its root, and every operation (search, insert, traversal) begins there. If you lose that reference, you lose access to the whole tree.
The root also fixes the direction of the structure. "Parent" and "child" only have meaning once you know which node is the root. The same set of connected nodes can be drawn with a different root, and the parent-child relationships change with it.
The root is also the reference point for measuring. The root has depth 0, and the depth of every other node is its distance from the root. A later chapter covers depth in full.
Finding the root in code
In the node class from this tutorial, children are stored but parents are not. A node therefore cannot tell you whether it is the root. You can find the root by collecting every node that appears as a child and returning the one node that is not in that collection.
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children or []
def find_root(nodes):
# Every node that is somebody's child is not the root.
pointed_to = {id(child) for node in nodes for child in node.children}
roots = [node for node in nodes if id(node) not in pointed_to]
if len(roots) != 1:
raise ValueError(f"expected exactly one root, found {len(roots)}")
return roots[0]
e, f, g = Node("E"), Node("F"), Node("G")
b = Node("B", [e, f])
c = Node("C")
d = Node("D", [g])
a = Node("A", [b, c, d])
shuffled = [e, b, g, c, a, d, f]
print(find_root(shuffled).value) # AThe function compares nodes by id, which identifies the object itself. Two different nodes may hold equal values, so comparing by value could give wrong answers. The check on len(roots) catches both failure cases described earlier: zero roots (a cycle) and several roots (a forest).
Common mistakes
- Treating a node with many children as the root. Having many children says nothing about being the root. Only having no parent does.
- Assuming the root is a leaf or an internal node by definition. A root with children is internal. A tree with a single node has a root that is also a leaf. The next chapters return to this case.
- Forgetting to keep a reference to the root when you replace it. If you insert a new node above the old root, the tree's stored root must be updated to the new node.
Exercise
A list of nodes contains X, Y, and Z. X has child Y, and Z has no children and is nobody's child. What does find_root do with this list, and why?
Show answer
It raises ValueError. Both X and Z are not pointed to by any node, so there are two parentless nodes. That means the structure is a forest of two trees, not a single tree, and find_root requires exactly one root.