Sub topic 8
Degree of a Node and of a Tree
This chapter assumes you can read the Node class from earlier chapters, with a value and a list of children. It also assumes you know what a parent, a child, and a leaf are.
Degree of a node
The degree of a node is the number of children it has. It counts only the edges that go down to its children. It does not count the edge up to the parent.
In the example tree, A has three children (B, C, D), so its degree is 3. B has two children, so its degree is 2. D has one child, so its degree is 1. C, E, F, and G have no children, so their degree is 0.
This gives a second way to define a leaf: a leaf is a node of degree 0. An internal node has degree 1 or more.
Degree of a tree
The degree of a tree is the largest degree of any node in it. For the example tree, the degrees are 3, 2, 0, 1, 0, 0, 0, so the tree has degree 3.
A tree of degree 2 is a binary tree, where each node has at most two children. A tree of degree 1 is just a chain.
Computing degree in code
The degree of a node is the length of its children list. The degree of the tree needs a walk over every node.
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children or []
def degree(node):
return len(node.children)
def tree_degree(node):
# The tree's degree is the largest degree found at this node
# or anywhere in its subtrees.
return max([degree(node)] + [tree_degree(c) for c in node.children])
tree = Node("A", [
Node("B", [Node("E"), Node("F")]),
Node("C"),
Node("D", [Node("G")]),
])
print(degree(tree)) # 3
print(degree(tree.children[0])) # 2
print(tree_degree(tree)) # 3Common errors
- Counting the parent edge. Degree counts children only. Some graph textbooks define the degree of a node as all its edges. In that sense, a non-root tree node has one more than its tree degree. Check which definition your source uses.
- Confusing degree with height or depth. Degree measures how wide a node branches. Depth and height measure vertical distance. A tree with degree 10 can still have height 1.
- Forgetting that the root counts. The root's children count toward the tree's degree like any other node's.
Exercise
A tree has a root with two children. The first child has four children. The second child is a leaf. All other nodes are leaves. What is the degree of the root, the degree of the first child, and the degree of the tree?
Show answer
The root has degree 2. The first child has degree 4. The tree's degree is the largest node degree, which is 4.