Sub topic 7
Subtrees
This chapter assumes you know the terms root, parent, child, leaf, ancestor, and descendant from the earlier chapters. It also assumes you can read a short recursive function.
What a subtree is
A subtree is a node together with all of its descendants and the edges between them. Pick any node v. The subtree rooted at v contains v and everything reachable by moving downward from v.
A subtree is itself a tree, and v is its root. This is why recursive tree code works. The same function can handle the whole tree and each of its subtrees.
In the example tree, the subtree rooted at B contains B, E, and F. The subtree rooted at C contains only C.
Subtrees in code
A node object already represents a subtree. Its children list holds the roots of smaller subtrees. You never need to copy anything to "get" a subtree. You only need a reference to its root.
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children or []
def subtree_size(node):
# The node itself, plus the size of each child's subtree.
return 1 + sum(subtree_size(child) for child in node.children)
tree = Node("A", [
Node("B", [Node("E"), Node("F")]),
Node("C"),
Node("D", [Node("G")]),
])
print(subtree_size(tree)) # 7
print(subtree_size(tree.children[0])) # 3 (subtree rooted at B)
print(subtree_size(tree.children[1])) # 1 (subtree rooted at C)The function has the usual recursive shape. The answer for a node is built from the answers for its children's subtrees.
Relationships to other terms
- Every node is the root of exactly one subtree.
- A leaf is the root of a subtree with one node.
- The subtree rooted at the tree's root is the whole tree.
- A proper subtree excludes the whole tree. It is rooted at any node other than the root.
- Node
uis a descendant ofvexactly whenubelongs to the subtree rooted atv. - The height of a node equals the height of the subtree rooted at it. The height of
Bis 1, and so is the height of the subtree rooted atB.
Common errors
- Leaving out the root of the subtree. The subtree rooted at
BincludesB. The descendants ofBare onlyEandF. Mixing these up gives off-by-one sizes. - Measuring depth inside a subtree with the wrong origin. Inside the subtree rooted at
B, nodeEhas depth 1. In the full tree,Ehas depth 2. Say which root you measure from. - Assuming a subtree is a copy. In the code above,
tree.children[0]is the same object the full tree uses. If you change it, the full tree changes too.
Exercise
Using the example tree, what are the size and height of the subtree rooted at D, and is it a proper subtree?
Show answer
The subtree rooted at D contains D and G, so its size is 2. Its height is 1, because D is one edge above its deepest leaf G. It is a proper subtree because its root D is not the root of the whole tree.