Binary trees and recursion
A binary tree is made of nodes with at most two children, left and right; its problems are written with recursion, where an empty tree returns 0 and the rest is handed to the two subtrees, so recursion goes as deep as the tree is tall.
Folders inside folders, tags inside tags on a web page, objects inside objects in JSON: all of them are trees. The most common kind is the binary tree, where each node has at most two children, a left one and a right one. Binary tree problems are almost always written with recursion: a function deals with the current node and hands the rest to the left subtree and the right subtree. The code is short; the price is that you must keep an eye on depth. A binary tree of a million nodes, kept as balanced as possible, has only 20 levels, so the recursion is at most 20 deep. Put the same million nodes in a line and the recursion needs a million levels, while Python raises RecursionError at about 1000 by default.
Nodes: val, left, right
A binary tree node is much like a linked-list node, with the one next replaced by two references: left points to the left child and right to the right child, and a missing child is None. The whole tree is reached through its top node alone, the root.
A few words: the whole tree below a node is one of its subtrees, so 2 with the 4 and 5 under it is 1's left subtree; a node with no children is a leaf; the height is how many levels there are from the root down to the deepest leaf (in this lesson an empty tree has height 0 and a root alone has height 1).
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7root = TreeNode(1,8 TreeNode(2, TreeNode(4), TreeNode(5)),9 TreeNode(3, None, TreeNode(6)))10print(root.val, root.left.val, root.right.val)11print(root.left.left.val, root.right.left, root.right.right.val)12leaf = root.left.left13print(leaf.left is None and leaf.right is None)
1 2 3 4 None 6 True
In the tree at the start of this stage (1 has children 2 and 3, 2 has children 4 and 5, 3 has only a right child 6), which nodes are leaves?
Building a tree from a list
Nested TreeNode(...) calls soon become unreadable. LeetCode and most problem sets describe a tree as a list instead: the values written level by level from the top, left to right in each level, with None where there is no node. The tree above is [1, 2, 3, 4, 5, None, 6].
The tree is built in the same order it is read: a queue holds the nodes that have not been given children yet; take one from the front each time and give it the next two values in the list as its left and right children.
1from collections import deque2 3class TreeNode:4 def __init__(self, val, left=None, right=None):5 self.val = val6 self.left = left7 self.right = right8 9def build(vals):10 if not vals or vals[0] is None:11 return None12 root = TreeNode(vals[0])13 q = deque([root])14 i = 115 while q and i < len(vals):16 node = q.popleft()17 if vals[i] is not None: # left child18 node.left = TreeNode(vals[i])19 q.append(node.left)20 i += 121 if i < len(vals) and vals[i] is not None: # right child22 node.right = TreeNode(vals[i])23 q.append(node.right)24 i += 125 return root26 27root = build([1, 2, 3, 4, 5, None, 6])28print(root.val, root.left.val, root.right.val)29print(root.left.left.val, root.left.right.val, root.right.left, root.right.right.val)30 31t = build([1, None, 2, 3])32print(t.left, t.right.val, t.right.left.val)
1 2 3 4 5 None 6 None 2 3
In [1, None, 2, 3], 1's left is empty and its right child is 2; the 3 that follows goes to the next node in the queue, which is 2. A None takes no child places: no two empty places are kept under a gap, so even a deep one-sided tree needs only about n values.
There is another way to store a tree: the node at index i, its children at 2i + 1 and 2i + 2, with empty places taking cells too. It suits a tree packed full (the heap of lesson 5); for a one-sided tree, 10 levels already take 1023 cells.
Building level by level, build([1, 2, 3, None, 4]). Whose child is 4, and which side?
A tree stored by index: a node at i has its children at 2i + 1 and 2i + 2. At which index is the parent of the node at index 4?
Trust the recursive call
How many nodes does a tree have? The root counts 1, plus the number of nodes in the left subtree and in the right subtree. The left subtree is a binary tree too, so the same function can count it. Writing recursion takes two things:
- The smallest case: an empty tree (
node is None) returns its answer straight away; - Every other case: assume the calls on the subtrees already return the right answers, and put the whole tree's answer together from them.
Point 2 is the key: when you write size(node.left), don't climb inside to see how it counts; trust it to be right. If point 1 is right and point 2 puts things together right, the whole function is right.
1from collections import deque2 3class TreeNode:4 def __init__(self, val, left=None, right=None):5 self.val = val6 self.left = left7 self.right = right8 9def build(vals):10 if not vals or vals[0] is None:11 return None12 root = TreeNode(vals[0])13 q = deque([root])14 i = 115 while q and i < len(vals):16 node = q.popleft()17 if vals[i] is not None:18 node.left = TreeNode(vals[i])19 q.append(node.left)20 i += 121 if i < len(vals) and vals[i] is not None:22 node.right = TreeNode(vals[i])23 q.append(node.right)24 i += 125 return root26 27def size(node):28 if node is None:29 return 030 return 1 + size(node.left) + size(node.right)31 32def height(node):33 if node is None:34 return 035 return 1 + max(height(node.left), height(node.right))36 37def total(node):38 if node is None:39 return 040 return node.val + total(node.left) + total(node.right)41 42root = build([1, 2, 3, 4, 5, None, 6])43print(size(root), height(root), total(root))44print(size(None), height(None))45print(height(build([1])), height(build([1, 2, None, 3])))
6 3 21 0 0 1 3
The three functions look almost the same and differ only in the line that puts things together: size is 1 + both sides added, height is 1 + the larger side, sum is node.val + both sides added.
When the program really runs, each call takes a level on the call stack and has to wait for its children to answer before it can go on. Here is the left half of height(root):
main()h = ?height(1)node = 1height(2)node = 2height(4)node = 4height(None)node = Noneheight(None)node = Noneheight(5)node = 5height(3)node = 3Write each call's answer under its node and you get a "recursion tree". Here it is for the sum, total:
Count how many times size is called in all (including size(None)). What does it print?
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7calls = 08 9def size(node):10 global calls11 calls += 112 if node is None:13 return 014 return 1 + size(node.left) + size(node.right)15 16root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),17 TreeNode(3, None, TreeNode(6)))18print(size(root), calls)
Pick one for the blank so that height works out the tree's height.
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7def height(node):8 if node is None:9 return 010 return 1 + (height(node.left), height(node.right))11 12root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))13print(height(root))
1 + max(...). On the left 1 → 2 → 4 is 3 levels, on the right 1 → 3 is only 2, so the height is 3.Count the leaves
✓Complete leaves(node): return how many leaves (nodes whose left and right are both None) the tree has. An empty tree returns 0.
3 1 0 1
1from collections import deque2 3class TreeNode:4 def __init__(self, val, left=None, right=None):5 self.val = val6 self.left = left7 self.right = right8 9def build(vals):10 if not vals or vals[0] is None:11 return None12 root = TreeNode(vals[0])13 q = deque([root])14 i = 115 while q and i < len(vals):16 node = q.popleft()17 if vals[i] is not None:18 node.left = TreeNode(vals[i])19 q.append(node.left)20 i += 121 if i < len(vals) and vals[i] is not None:22 node.right = TreeNode(vals[i])23 q.append(node.right)24 i += 125 return root26 27def leaves(node):28 # empty tree: 0; a leaf: 1; anything else: both sides added29 return 030 31print(leaves(build([1, 2, 3, 4, 5, None, 6])))32print(leaves(build([1])), leaves(None), leaves(build([1, 2, None, 3])))
The largest value
✓Complete max_val(node): return the largest val in the tree. An empty tree returns float("-inf"), which is smaller than anything, so putting the answer together needs no special case.
15 -2 -inf
1from collections import deque2 3class TreeNode:4 def __init__(self, val, left=None, right=None):5 self.val = val6 self.left = left7 self.right = right8 9def build(vals):10 if not vals or vals[0] is None:11 return None12 root = TreeNode(vals[0])13 q = deque([root])14 i = 115 while q and i < len(vals):16 node = q.popleft()17 if vals[i] is not None:18 node.left = TreeNode(vals[i])19 q.append(node.left)20 i += 121 if i < len(vals) and vals[i] is not None:22 node.right = TreeNode(vals[i])23 q.append(node.right)24 i += 125 return root26 27def max_val(node):28 # empty tree: float("-inf"); otherwise the largest of itself, the left's max and the right's max29 return 030 31print(max_val(build([3, 9, 2, None, None, 7, 15])))32print(max_val(build([-5, -2, -8])), max_val(None))
Recursion goes as deep as the tree is tall
There are always 2n + 1 calls whatever the tree looks like, so the time is always O(n). What differs is how deep the stack goes: the recursion only starts returning once it reaches the deepest None, so the stack has as many levels as the tree's height plus 1. The same 127 nodes as a full binary tree and as a line are very different:
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7def chain(n): # each node has only a right child: a line8 root = None9 for v in range(n, 0, -1):10 root = TreeNode(v, None, root)11 return root12 13def balanced(lo, hi): # lo..hi built as balanced as possible14 if lo > hi:15 return None16 mid = (lo + hi) // 217 return TreeNode(mid, balanced(lo, mid - 1), balanced(mid + 1, hi))18 19deepest = 020calls = 021 22def size(node, depth=1):23 global deepest, calls24 calls += 125 deepest = max(deepest, depth)26 if node is None:27 return 028 return 1 + size(node.left, depth + 1) + size(node.right, depth + 1)29 30for name, root in [("balanced", balanced(1, 127)), ("a line", chain(127))]:31 deepest = calls = 032 print(name, "nodes", size(root), "calls", calls, "deepest", deepest, "levels")
balanced nodes 127 calls 255 deepest 8 levels a line nodes 127 calls 255 deepest 128 levels
Both take 255 calls, yet one stack is 8 levels and the other 128. With a million nodes, the balanced tree needs only 21 levels; the line needs a million, far beyond Python's recursion limit. When does a tree grow into a line? Lesson 4 shows it: insert sorted numbers into a binary search tree one by one.
| A balanced tree (n nodes) | A line (n nodes) | |
|---|---|---|
| Height h | about log₂ n | n |
| Recursive calls | 2n + 1 | 2n + 1 |
| Time | O(n) | O(n) |
| Stack depth (extra space) | O(log n) | O(n) |
| Stack levels at n = 1 million | 21 | 1 million: RecursionError |
In interviews: for a recursive tree solution, give two costs: time O(n) (once per node) and space O(h) (the recursion stack, h being the height), O(log n) at best and O(n) at worst. "What happens when the tree degenerates into a linked list?" is a common follow-up.
A binary tree of height 7 (a tree with just a root has height 1): at most how many nodes can it have?
Finding the size of an n-node tree recursively: when the tree is a single line, how much extra space (the recursion stack) does it take?
How you write it at work
The standard library has no binary tree class: at work, trees are mostly ready-made nested data (the dicts and lists parsed from JSON, xml.etree elements, ast syntax trees), and for balanced ordered structures there are dicts, bisect on a sorted list, or the third-party sortedcontainers. Writing your own TreeNode is mostly for interviews and courses.
If you really must handle a tree that may be very deep (data from someone else that is not guaranteed to be balanced), remember that recursion has a limit:
1def depth(n):2 if n == 0:3 return 04 return 1 + depth(n - 1)5 6try:7 depth(100000)8except RecursionError:9 print("RecursionError: recursion too deep")10 11class TreeNode:12 def __init__(self, val, left=None, right=None):13 self.val = val14 self.left = left15 self.right = right16 17def size_iter(root): # a list as our own stack: no depth limit18 count = 019 stack = [root]20 while stack:21 node = stack.pop()22 if node is not None:23 count += 124 stack.append(node.left)25 stack.append(node.right)26 return count27 28root = None29for v in range(1000, 0, -1): # a line 1000 levels deep30 root = TreeNode(v, None, root)31print(size_iter(root))
RecursionError: recursion too deep 1000
- When you can't be sure how deep a tree is, rewrite the recursion as a loop with your own stack (a list) or queue (a deque); the next lesson does exactly that.
sys.setrecursionlimitraises the limit, but raise it too far and the interpreter's own stack bursts first and the whole process crashes. It is not a fix.- To count something inside a recursive function (like
callsabove), useglobalornonlocal, or simply return it.
You need to handle a tree that may be very deep and isn't guaranteed to be balanced. Which approach is the safest?
Summary
Binary trees: left and right on every node, worked out by recursion
- TreeNode has val, left and right; a missing child is None, and the tree keeps only its root
- A problem's [1, 2, None, 3] is written level by level, left to right; build it with a queue handing out children
- Recursion takes two things: an empty tree returns at once; otherwise trust the subtree calls and put their answers together
- 2n + 1 calls, O(n) time; stack depth = tree height, and a tree shaped like a line raises RecursionError
1def height(node):2 if node is None:3 return 04 return 1 + max(height(node.left), height(node.right))