Tree recursion patterns: height, diameter, same tree, invert
🌍 In real life. The head teacher wants to know how many layers of staff the school has. She doesn't walk the whole building. She asks each deputy, "how many layers are there from you down?" Each deputy asks the teachers under them the same question, and so on. A teacher with nobody under them answers 1. Each person takes the bigger answer from below and adds 1 for themselves, and the head gets her answer.
That is the pattern behind almost every tree problem: ask each child, then combine the answers. This lesson uses it four times: for a tree's height, its widest path, checking whether two trees are the same, and turning a tree into its mirror image.
The idea in one sentence: solve a tree problem by deciding what the answer is for an empty tree, and how to build a node's answer from its left and right subtrees' answers; recursion does the rest.
Its words:
- base case: the answer for an empty tree (
None) - combine step: how a node's answer comes from its children's answers
- height: 1 + the bigger of the two subtrees' heights; an empty tree's height is 0
- diameter: the number of branches on the longest path between any two nodes; the path may or may not pass through the root
- same tree: two trees with the same shape and the same value at every place
- invert (mirror): swap the left and right child of every node
How it works, step by step, for height:
- if the node is
None, the answer is 0 - ask the left subtree for its height, and the right subtree for its height
- the answer is 1 + the bigger of the two
The children must answer first, so the work is done in postorder. Watch each node's height appear only after its children's:
Inverting uses the same pattern: every node's two children get swapped, and each child is inverted too. The animation swaps on the way down, one node per step; the code below inverts the two subtrees first and swaps them afterwards. Every node is swapped exactly once either way, so swapping before or after recursing gives the same mirror image. A subtree moves as one piece, with everything under it:
Why it is correct. Think of it like the head teacher: if each subtree's answer is right, the node's answer built from them is right. The subtrees are smaller trees, so the same reasoning applies to them, all the way down to the empty tree, whose answer we wrote by hand. For the diameter, the longest path between two nodes always bends at one highest node: it goes down the left side as far as possible and down the right side as far as possible. At a node, that is height(left) + height(right) branches. So the diameter is the biggest of those numbers over all the nodes, and we can collect it while working out the heights.
What it costs, by counting. Each of these functions visits each node once and does a fixed amount of work there, so each is O(n). Be careful when one recursion calls another: a diameter that calls height() separately at every node costs n + (n − 1) + … + 1 = n(n + 1)/2 steps on a chain, 500,500 for 1,000 nodes, which is O(n²). The version below gets the heights and the diameter in the same single pass: O(n). Its inner function h updates best, a name of diameter, so it says nonlocal best first (Lesson 16.5).
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def height(node):
if node is None:
return 0 # an empty tree has no levels
return 1 + max(height(node.left), height(node.right))
def same_tree(a, b):
if a is None and b is None:
return True # two empty trees match
if a is None or b is None:
return False # one is empty, the other isn't
return a.val == b.val and same_tree(a.left, b.left) and same_tree(a.right, b.right)
def invert(node):
if node is None:
return None
node.left, node.right = invert(node.right), invert(node.left)
return node
def diameter(root):
best = 0
def h(node): # the height, and on the way the longest path through node
nonlocal best
if node is None:
return 0
left, right = h(node.left), h(node.right)
best = max(best, left + right) # branches on the longest path that bends at node
return 1 + max(left, right)
h(root)
return best
root = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print(height(root))
print(diameter(root)) # 4 → 2 → 1 → 3 → 6
copy = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print(same_tree(root, copy))
invert(root)
print(root.left.val, root.right.val, root.left.left.val)
print(same_tree(root, copy))Mistakes and edge cases.
- inverting in two lines:
node.left = invert(node.right)thennode.right = invert(node.left)reads the new left child, so both sides end up as the old right subtree; swap both at once witha, b = b, a - same tree, values only: comparing just the values in some order misses the shape;
Node(1, Node(2))andNode(1, None, Node(2))hold the same values but are different trees - the diameter through the root only: the longest path may bend lower down, inside one subtree; take the best over all nodes
- height counted in branches: some books give a single node height 0 and an empty tree −1; be sure which one a problem uses
- an empty tree: height 0, diameter 0, inverted it is still
None, and it is the same tree as another empty tree
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 height(node): if node is None: return 0 # an empty tree has no levels return 1 + max(height(node.left), height(node.right)) print(height(Node(1, Node(2, None, Node(3, Node(4))))))Same values, different shape. What does this print?
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def same_tree(a, b): if a is None and b is None: return True # two empty trees match if a is None or b is None: return False # one is empty, the other isn't return a.val == b.val and same_tree(a.left, b.left) and same_tree(a.right, b.right) print(same_tree(Node(1, Node(2)), Node(1, None, Node(2))))What is the diameter of this tree? (Its root has only a left child.)
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def diameter(root): best = 0 def h(node): # the height, and on the way the longest path through node nonlocal best if node is None: return 0 left, right = h(node.left), h(node.right) best = max(best, left + right) # branches on the longest path that bends at node return 1 + max(left, right) h(root) return best root = Node(1, Node(2, Node(4, Node(7)), Node(5, None, Node(8)))) print(diameter(root))After this, both of the root's children are the same subtree: the old right one, inverted. Which line reads a child that has already been replaced?
def invert(node): if node is None: return None node.left = invert(node.right) node.right = invert(node.left) return nodeA diameter function calls a separate height() at every node. How does its work grow on a chain of n nodes?
- O(n²): about n(n + 1)/2 steps
- O(n)
- O(log n)
Coding tasks
Write
height(root): the number of levels in the tree (an empty tree is 0, a single node is 1).Write
same_tree(a, b):Trueif the two trees have the same shape and the same value in every place, otherwiseFalse.Write
invert(root): turn the tree into its mirror image by swapping the left and right child of every node, and return the root (Nonefor an empty tree).