Size, height and max with recursion
After this: Write size, height and max by trusting the smaller calls.
On this page · 9 sections · 4 checks
You can now walk a tree in several orders. Often, though, you do not want a list of nodes. You want one answer about the whole tree. How many nodes does it have? How tall is it? What is the largest value? A fact like this about a tree is called a property.
There is a neat way to work these out. Each subtree can give its own answer, and you combine the answers.
Counting the tiny tree
How many nodes are in this tree? We will call this number its size.
Imagine you are node 1, and you can only see your two children. You ask each of them how many nodes are in their subtree.
- Node 2 has no children. Both its sides are empty, and an empty tree has 0 nodes. So node 2 answers 1 + 0 + 0 = 1.
- Node 3 is the same, so it answers 1 + 0 + 0 = 1.
- You add yourself to the two answers: 1 + 1 + 1 = 3.
So the size is 3. Here is the rule: the size of a tree is 1, plus the size of the left subtree, plus the size of the right subtree. The size of an empty tree is 0.
Notice that node 1 did not count the nodes below it. It asked, and it trusted the answers. The asking is a recursive call. The one answer you must get right yourself is the base case, the answer for an empty tree.
Size of the example tree
Here is the same rule on the six-node tree. Each row uses answers from the rows above it.
| Node | Left answer | Right answer | Size: 1 + left + right |
|---|---|---|---|
| 4 | 0 | 0 | 1 |
| 5 | 0 | 0 | 1 |
| 2 | 1 | 1 | 3 |
| 6 | 0 | 0 | 1 |
| 3 | 0 | 1 | 2 |
| 1 | 3 | 2 | 6 |
Read the first column from top to bottom: 4, 5, 2, 6, 3, 1. That is postorder. Each node can answer only after both of its children have answered.
Height needs a different base case
The height of a tree is one edge more than the height of its taller subtree. So the rule is 1 + the larger of the left height and the right height.
What should an empty tree give? We can work it out from a case we already know.
- A single node has height 0, as the parts of a tree lesson said.
- A single node has two empty subtrees. Call the height of an empty tree e.
- So the rule says 1 + the larger of e and e, which is 1 + e, must equal 0.
- That means e is −1.
So an empty tree has height −1. The number is there to make the rule come out right. Here is the example tree.
| Node | Left answer | Right answer | Height: 1 + the larger |
|---|---|---|---|
| 4 | −1 | −1 | 0 |
| 5 | −1 | −1 | 0 |
| 2 | 0 | 0 | 1 |
| 6 | −1 | −1 | 0 |
| 3 | −1 | 0 | 1 |
| 1 | 1 | 1 | 2 |
The last row gives 2, which matches the height you measured by counting edges.
The largest value
The largest value in a tree is the largest of three things: this node's value, the largest in the left subtree, and the largest in the right subtree.
An empty tree has no values, so what should it give? It should give something that can never beat a real value: float("-inf")Integer.MIN_VALUE. That is minus infinity, which is smaller than any number.That is the smallest int there is, so no node's value can be smaller.
The code
Here are all three. Each one has the same shape: a base case, then one line that asks both subtrees and combines the answers.
def size(node): if node is None: return 0 # an empty tree has no nodes return 1 + size(node.left) + size(node.right)
def height(node): if node is None: return -1 # so that a single node has height 0 return 1 + max(height(node.left), height(node.right))
def tree_max(node): if node is None: return float("-inf") # minus infinity: smaller than any number return max(node.value, tree_max(node.left), tree_max(node.right))static int size(Node node) { if (node == null) return 0; // an empty tree has no nodes return 1 + size(node.left) + size(node.right);}
static int height(Node node) { if (node == null) return -1; // so that a single node has height 0 return 1 + Math.max(height(node.left), height(node.right));}
static int treeMax(Node node) { if (node == null) return Integer.MIN_VALUE; // the smallest int there is return Math.max(node.value, Math.max(treeMax(node.left), treeMax(node.right)));}The highlighted lines are the base cases. Compare the last line of each function.
sizeadds the two answers and adds 1 for this node.heightkeeps the larger answer and adds 1 for the edge down to it.- tree_maxtreeMax compares the node's own value with the two answers.
print(size(root), height(root), tree_max(root))6 2 6
System.out.println(size(root) + " " + height(root) + " " + treeMax(root));6 2 6
Each function makes one call for each node, plus one for each missing child, and does a small amount of work in each call. So each one costs O(n), and the stack gets as deep as the tree is tall.
Why trusting is allowed
Why can size use size(node.left) before that number exists? Because it is the same function on a smaller tree. The calls get smaller until they reach the empty subtrees, where the base case gives the answer directly. Then each call has what it needs, all the way back up.
So you need to check only two things: that the base case is right, and that the combining step is right. This is the "trust the smaller call" habit from the recursion tutorial. Trees are where it helps the most, because a walk with a loop needs its own stack, and recursion already has the call stack.
Watch it happen
Watch the values come back up. A leaf settles first, then its parent, and the root settles last.
- Count the nodesSize. A leaf settles first: 4 gives 1 + 0 + 0 = 1. Then 2 combines its children: 1 + 1 + 1 = 3.
- Measure the height
- Find the maximum
Run an operation to begin.
Check yourself
With the three functions above defined, what does this print for the example tree?
print(size(root), height(root), tree_max(root))System.out.println(size(root) + " " + height(root) + " " + treeMax(root));size(node) returns 1 + size(node.left) + size(node.right). How can it use size(node.left) when the left subtree has not been counted yet?
height returns −1 for an empty tree. Why that, and not 0?
height is missing its recursive line. It should return one more than the height of the taller subtree.
def height(node): if node is None: return -1 ______________________________ # ← one more than the taller subtreestatic int height(Node node) { if (node == null) return -1; ______________________________ // ← one more than the taller subtree}Connect
- Work out size, height and the largest value in three moves: ask the left subtree, ask the right subtree, combine the answers with this node.
- Choose the base case that makes the combining step come out right: 0 for size, −1 for height, and the smallest possible value for the largest value (minus infinity in Python, Integer.MIN_VALUE in Java).
- Explain why you can trust the recursive call: it is the same function on a smaller tree.