Tree words: root, child, leaf, height, depth
🌍 In real life. Draw your family tree with your grandmother at the top: under her, her children; under each of them, their children. Or open the folders on a computer: Documents holds School and Photos, and School holds Maths and Bangla. Both pictures have the same shape. One thing sits at the top, everything else hangs under exactly one thing above it, and you never go round in a circle.
That shape is a tree, drawn upside down: the root at the top, the leaves at the bottom. Folders, a book's chapters and sections, a company's managers, the HTML of a web page and the moves of a game are all trees, so this chapter and the next three are about them.
The idea in one sentence: a tree is a set of nodes joined by branches, where one node, the root, has no parent and every other node has exactly one; in a binary tree each node has at most two children, a left one and a right one.
Its words:
- node: one item in the tree, holding a value
- branch (also called an edge): the link from a parent to a child
- root: the one node with no parent, at the top
- parent and child: a node and a node directly under it; children of the same parent are siblings
- leaf: a node with no children
- subtree: a node together with everything under it; every child is the root of its own subtree
- depth of a node: the number of branches from the root down to it (the root's depth is 0)
- height of a tree: the number of levels, which is the number of nodes on the longest path down from the root (an empty tree's height is 0). Some books count branches instead of nodes, so their height is one less; this course counts nodes, as LeetCode's "maximum depth" does.
In Python, a node is a small object with a value and two links, and None means "no child here":
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
# gran
# / \
# ma uncle
# / \
# ana bo
root = Node("gran", Node("ma", Node("ana"), Node("bo")), Node("uncle"))
print(root.val) # the root
print(root.left.val, root.right.val)
print(root.left.left.val) # gran's first grandchild
print(root.right.left) # uncle has no childrenHow to read a tree, step by step:
- the root is the node you hold: here
root, with the value"gran" - its children are
root.leftandroot.right; follow.leftand.rightto go down one level - a child that is
Noneis missing; a node whose two children are bothNoneis a leaf - the depth of a node is how many
.leftor.rightsteps it takes to reach it from the root - the height is the number of levels: count the nodes on the longest way down
LeetCode writes a tree as one list, level by level, with null for a missing child: this family is ["gran", "ma", "uncle", "ana", "bo"], and [1, 2, 3, null, 4] is 1 with children 2 and 3, where 2 has only a right child, 4. The animations in this chapter take trees written that way. Watch each part named in turn:
Why a tree is so easy to work with. Every node except the root has exactly one parent, so from the root there is exactly one way down to each node: no loops, no two routes. That means a tree is just a root with two smaller trees hanging under it, its left subtree and its right subtree (either may be empty). So almost every question about a tree has a recursive answer: answer it for the two smaller trees, then combine. Counting the nodes is 1 for the root plus the count of each subtree, and an empty tree has 0 nodes. The recursion always ends, because each call is on a smaller tree, and the smallest tree, None, is the base case.
What it costs, by counting. count calls itself once for each node and once for each missing child, so for n nodes it makes 2n + 1 calls: O(n). How many nodes fit in h levels? Each level can hold twice as many as the one above:
- 1 level: at most 1 node
- 2 levels: 1 + 2 = 3
- 3 levels: 1 + 2 + 4 = 7
- 4 levels: 15
- 10 levels: 1,023
- 20 levels: 1,048,575
So a full tree with h levels has 2ʰ − 1 nodes, and a million nodes need only 20 levels when the tree is bushy. But a tree can also be a thin chain, each node with one child: then n nodes make n levels. How tall a tree is decides how fast many tree algorithms are, as Chapter 48 shows.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count(node):
if node is None:
return 0 # an empty tree has no nodes
return 1 + count(node.left) + count(node.right)
def leaves(node):
if node is None:
return []
if node.left is None and node.right is None:
return [node.val] # no children: a leaf
return leaves(node.left) + leaves(node.right)
root = Node("gran", Node("ma", Node("ana"), Node("bo")), Node("uncle"))
print(count(root))
print(leaves(root))
print(count(None)) # the empty treeMistakes and edge cases.
- no base case for
None:count(node.left)on a leaf callscount(None), andNone.leftraisesAttributeError: 'NoneType' object has no attribute 'left'; always start withif node is None - testing for a leaf instead of for
None:if node.left is None and node.right is None: return 1works for leaves but crashes on a node with only one child, because the other side is stillNone - depth and height mixed up: depth is measured from the root down to one node (the root is 0); height is a property of a whole tree, counted in levels (a single node is 1)
- the empty tree:
root = Noneis a real tree with 0 nodes and height 0; your functions should handle it ==versusis: compare values with==(node.val == x) and check for a missing child withis None
Quiz
What does this print?
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def count(node): if node is None: return 0 # an empty tree has no nodes return 1 + count(node.left) + count(node.right) root = Node(5, Node(3, None, Node(4)), Node(8)) print(count(root), root.left.right.val)The tree [1, 2, 3, null, 4]: which nodes are leaves?
- 3 and 4
- 2 and 3
- Only 4
In the same tree [1, 2, 3, null, 4], what is the depth of 4, and the height of the tree?
- Depth 2, height 3
- Depth 3, height 3
- Depth 2, height 2
At most how many nodes can a binary tree with 4 levels have?
- 15
- 8
- 16
This works on leaves but crashes with AttributeError on Node(1, Node(2)), a node with only one child. Which line is wrong?
def count(node): if node.left is None and node.right is None: return 1 return 1 + count(node.left) + count(node.right)
Coding tasks
Using the
Nodeclass, writecount_nodes(root): the number of nodes in the tree (0for an empty tree,root = None).Write
leaves(root): the values of all the leaves, from left to right, as a list ([]for an empty tree).Folders form a tree. Write
depth_of(root, x): the depth of the node whose value isx(the root is at depth 0), or-1ifxis not in the tree. The values are all different.