Sub topic 3
Representing nodes and trees in code
This chapter assumes you know Python classes, references (variables that point to objects), recursion, and the idea of a binary tree with a root and left and right children. It shows how to turn the binary search tree (BST) ordering property into data structures you can run.
A node is a key and two references
A BST is built from nodes. Each node holds one key and two references: one to the left child and one to the right child. A reference that is None means "no child here."
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = NoneThe tree itself is just a reference to the root node. An empty tree is None. You do not need a separate tree class to start. Every node is the root of its own subtree, so a function that accepts a node can work on a whole tree or on any part of it.
Why this shape works
The ordering property says that for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger. The node layout makes this easy to use. At any node you compare one key and then follow exactly one reference. The other subtree is never visited.
Because a subtree has the same shape as the whole tree, most operations have a natural recursive form. The base case is None. The recursive case works on node.left or node.right.
Search and insert on this structure
Search walks down from the root. It needs no recursion, because it only ever moves in one direction.
def search(node, key):
while node is not None and node.key != key:
node = node.left if key < node.key else node.right
return nodeIt returns the matching node, or None if the key is absent.
Insertion is recursive. It finds the empty position where the key belongs and returns the root of the updated subtree.
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return nodeNote the assignments such as node.left = insert(node.left, key). If the child already exists, insert returns that same child and nothing changes. If the child is None, insert returns a new node and the assignment attaches it. Equal keys fall through both branches and are ignored, so this tree stores no duplicates.
Building a tree
The caller must keep the returned root. The root changes only when the tree is empty.
root = None
for k in [50, 30, 70, 20, 40]:
root = insert(root, k)
print(root.key) # 50
print(root.left.key) # 30
print(search(root, 40).key) # 40
print(search(root, 99)) # NoneCommon errors
- Discarding the return value. Writing
insert(root, 5)on an empty tree does nothing useful, because the new root is thrown away. Always writeroot = insert(root, 5). - Forgetting the base case. A recursive function that does not check
node is Nonefails withAttributeErrorwhen it reaches a missing child. - Comparing the wrong things. Compare keys, not nodes. If you store records, compare a specific field.
- Checking only a node's direct children. A tree is a valid BST only if every key in a subtree respects the bound set by all its ancestors. A node's own children can look correct while a deeper descendant breaks the rule.
A wrapper class
If you prefer an object that owns the root, wrap it. The node functions stay the same.
class BST:
def __init__(self):
self.root = None
def add(self, key):
self.root = insert(self.root, key)
def __contains__(self, key):
return search(self.root, key) is not NoneNow tree = BST(), tree.add(10), and 10 in tree all work, and callers never handle the root themselves.
Exercise
You run insert(root, 25) on a non-empty tree and ignore the return value. The tree already has a root. Is the key 25 still added? When would ignoring the return value lose data?
Show answer
Yes, the key is still added. The root is non-empty, so the recursion attaches a new node to an existing node's left or right reference, and the original root object is returned unchanged. Ignoring the return value loses data only when the tree is empty (root is None), because then the new node is the root and the caller's variable still points to None.