Sub topic 2
Representing a Binary Tree with Nodes
This chapter assumes you know basic Python classes, how references work, and the vocabulary from the previous chapter: root, leaf, parent, child and subtree. You will build a node class and a small tree by hand. The other chapters in this tutorial reuse that tree.
The node
A binary tree is a set of nodes. Each node stores a value and at most two links, one to a left child and one to a right child. A missing child is stored as None.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = rightThe left and right defaults mean you can create a leaf with Node(4). A leaf is a node whose two links are both None.
Building a tree by hand
You build a tree from the bottom up. Create the children first, then pass them to the parent's constructor.
# 1
# / \
# 2 3
# / \
# 4 5
root = Node(1, Node(2, Node(4), Node(5)), Node(3))The variable root holds a reference to the node with value 1. The whole tree is reachable from that one reference. If you lose it, you lose access to the tree.
Following links
You move through the tree by following left and right. Each step goes from a parent to a child.
print(root.value) # 1
print(root.left.value) # 2
print(root.left.right.value) # 5
print(root.right.left) # NoneThe last line prints None because node 3 is a leaf. Reading .value on that result would raise AttributeError. Check for None before you follow a link.
Why the structure is recursive
Every node is the root of its own subtree. root.left is a complete binary tree whose root is node 2. An empty tree is just None. This gives you the usual shape of tree code: handle None as the base case, then act on the node and its two subtrees.
def count_nodes(node):
if node is None:
return 0
return 1 + count_nodes(node.left) + count_nodes(node.right)
print(count_nodes(root)) # 5Common errors
- Checking
if node.left:when you meanif node.left is not None:. If you later giveNodea method such as__len__or__bool__, truthiness can change. The explicitis not Nonetest is safer. - Forgetting the
Nonebase case. A function that readsnode.leftwithout first checkingnoderaisesAttributeErrorat every leaf's missing child. - Sharing one node in two places. If you attach the same
Nodeobject as a child of two parents, the structure is no longer a tree. It is a graph, and traversals may visit that node twice. - Using mutable default arguments for children. Defaults of
Noneare correct here. Do not writeleft=[].
Exercise
Write a function count_leaves(node) that returns the number of leaves in a tree. What does it return for the example tree?
Show answer
A leaf has both children None. The function is: def count_leaves(node): then if node is None: return 0, then if node.left is None and node.right is None: return 1, then return count_leaves(node.left) + count_leaves(node.right). For the example tree it returns 3, for nodes 4, 5 and 3.