Module 8 · Trees and Heaps · Lesson 25 of 40
Trees: data with branches
Roots, children, leaves and height. Binary trees and the kinds you'll meet: full, complete, perfect, balanced and skewed.
In this lesson · about 20 minutes
- Use the words root, parent, child, leaf, depth and height
- Build a small binary tree in Python
- Find a tree's height with recursion
Lists, stacks and queues are all in a line. A tree branches, like a family tree or the folders on your computer.
Tree words
| Word | Meaning |
|---|---|
| Node | One item in the tree |
| Root | The top node (yes, computer trees grow upside down!) |
| Parent / child | A node and the nodes directly below it |
| Leaf | A node with no children |
| Edge | The link between a parent and a child |
| Depth of a node | How many edges from the root down to it |
| Height of a tree | The number of levels (or edges) on the longest path from the root to a leaf |
| Subtree | A node and everything below it: a smaller tree |
A tree with n nodes always has n − 1 edges, and there is exactly one path between any two nodes.
Binary trees
In a binary tree, each node has at most two children: left and right.
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# 1
# / \
# 2 3
# /
# 4
root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))
Kinds of binary trees
- Full: every node has 0 or 2 children.
- Complete: every level is full except maybe the last, which fills from the left. (Heaps are complete.)
- Perfect: all levels completely full.
- Balanced: left and right sides have about the same height everywhere, so the height is about log n.
- Skewed: every node has only one child. It is really just a linked list, with height n.
Try it: height and size with recursion
Trees are made for recursion: a tree is a root plus two smaller trees.
Exercise
Count the leaves
Write count_leaves(node) that returns the number of leaves (nodes with no children). A TreeNode class and build_tree helper are ready: build_tree([1, 2, 3, 4]) builds the tree from the lesson.
Code that runs before yours
from collections import deque
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_tree(values):
"""Build a tree from a level-order list such as [1, 2, 3, None, 4]."""
if not values or values[0] is None:
return None
root = TreeNode(values[0])
queue = deque([root])
i = 1
while queue and i < len(values):
node = queue.popleft()
if i < len(values) and values[i] is not None:
node.left = TreeNode(values[i])
queue.append(node.left)
i += 1
if i < len(values) and values[i] is not None:
node.right = TreeNode(values[i])
queue.append(node.right)
i += 1
return root
Exercise
Add up a tree
Write tree_sum(node) that returns the total of all values in the tree.
Code that runs before yours
from collections import deque
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_tree(values):
"""Build a tree from a level-order list such as [1, 2, 3, None, 4]."""
if not values or values[0] is None:
return None
root = TreeNode(values[0])
queue = deque([root])
i = 1
while queue and i < len(values):
node = queue.popleft()
if i < len(values) and values[i] is not None:
node.left = TreeNode(values[i])
queue.append(node.left)
i += 1
if i < len(values) and values[i] is not None:
node.right = TreeNode(values[i])
queue.append(node.right)
i += 1
return root
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.