Sub topic 10
Levels of a Tree
This chapter assumes you know what depth is: the number of edges on the path from the root to a node. It also assumes you can read the Node class used earlier in this tutorial, where each node holds a value and a list of children.
What a level is
A level is the set of all nodes that have the same depth. Level 0 holds only the root. Level 1 holds the root's children. Level 2 holds the grandchildren, and so on.
Levels give you a way to talk about a whole row of the tree at once, instead of one node at a time. Depth describes a single node. Level describes a group.
For the example tree from earlier:
| Level | Nodes |
|---|---|
| 0 | A |
| 1 | B, C, D |
| 2 | E, F, G |
Every node in a level has the same depth, so the two numbers are always equal for a given node. The difference is in what you are naming: a node's depth, or the group that shares it.
Level numbering conventions
Some sources start counting levels at 1 instead of 0. In that style, the root is on level 1 and the example tree has three levels. This matches the node-counting convention from the chapter on counting conventions.
This tutorial uses 0-based levels, so level equals depth.
Grouping nodes by level
You can build the level table in code by reusing the depth idea. A breadth-first traversal visits the tree one level at a time, using a queue. Each pass of the outer loop handles exactly one level.
from collections import deque
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children or []
def levels(root):
# Return a list of lists. Index i holds the values on level i.
if root is None:
return []
result = []
queue = deque([root])
while queue:
level_values = []
for _ in range(len(queue)): # the queue holds exactly one level here
node = queue.popleft()
level_values.append(node.value)
queue.extend(node.children)
result.append(level_values)
return result
tree = Node("A", [
Node("B", [Node("E"), Node("F")]),
Node("C"),
Node("D", [Node("G")]),
])
print(levels(tree))
# [['A'], ['B', 'C', 'D'], ['E', 'F', 'G']]The key line is for _ in range(len(queue)). Before the loop starts, the queue contains only the nodes of the current level. The loop removes exactly those nodes and adds their children, which form the next level.
Levels and height
The number of levels is one more than the height of the tree, when height counts edges. The example tree has height 2 and three levels. The last level holds the deepest leaves, so len(levels(tree)) - 1 gives the tree height.
An empty tree has no levels, and levels(None) returns an empty list.
Exercise
A tree has 4 levels numbered from 0. What is its height in edges, and what is the depth of a node on the last level?
Show answer
The levels are 0, 1, 2 and 3. The height is 3 edges, and a node on the last level has depth 3.
Exercise
In levels, what would go wrong if the inner loop used while queue instead of for _ in range(len(queue))?
Show answer
The loop would keep removing nodes and adding their children without stopping at a level boundary. The result would be one flat list of all values, and the level groups would be lost.