Sub topic 5
Paths Between Nodes
This chapter assumes you can write recursive functions and are comfortable with objects that hold references to other objects. You should also know the root, parent, and child vocabulary from the earlier chapters.
What a path is
A path is a sequence of nodes in which each consecutive pair is connected by an edge. In a tree, the edges only go between a parent and a child, so a path that never revisits a node moves steadily up or steadily down, or goes up and then down.
The length of a path is the number of edges it uses. A path with one node has length 0. This chapter counts edges, which is the convention used in the code examples of this tutorial.
Using the example tree from the previous chapter:
The sequence A, B, E is a path of length 2. The sequence E, B, F is also a path, also of length 2. It goes up to B and then down to F.
The unique path property
A tree has exactly one simple path between any two nodes. A simple path is one that does not visit any node twice. This property is what separates a tree from a general graph. It is also why depth is well defined: the distance from the root to a node is the length of the only simple path between them.
If a structure gave you two different simple paths between the same pair of nodes, it would contain a cycle, and it would not be a tree.
Downward paths
Most tree algorithms care about downward paths, which start at a node and follow child links. The code below finds the path from the root to a target value. It returns a list of values, or None if the target is not in the tree.
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children or []
def find_path(node, target):
# Return the list of values from node down to target, or None.
if node.value == target:
return [node.value]
for child in node.children:
rest = find_path(child, target)
if rest is not None:
return [node.value] + rest
return None
tree = Node("A", [
Node("B", [Node("E"), Node("F")]),
Node("C"),
Node("D", [Node("G")]),
])
print(find_path(tree, "G")) # ['A', 'D', 'G']
print(find_path(tree, "X")) # NoneThe function checks the current node first. If it is not the target, it asks each child for a path. The first child that finds the target returns its partial path, and the current node adds itself to the front.
The length of the returned path is len(path) - 1. For ['A', 'D', 'G'] that is 2.
Common errors
- Counting nodes instead of edges. The path A, D, G has three nodes but length 2.
- Assuming a path must start at the root. A path can start and end at any two nodes.
- Forgetting the
Nonecheck. An empty list is a valid result in some designs, so check explicitly withis not Noneas above. - Following child links upward. Nodes in this class do not store a parent, so a path that goes up needs either a parent reference or a search from the root.
Exercise
In the example tree, what is the simple path from E to G, and what is its length in edges?
Show answer
The path is E, B, A, D, G. It goes up from E to B and A, then down to D and G. It uses 4 edges, so its length is 4.