Specifically, I'm confused about the recursive calls inside the max function. What is max comparing on each iteration and how is the output able to be added to 1 without causing a TypeError?
You’re calling a function twice, and passing the return values of those two function calls to max. So, max is comparing whatever this function returns.
If that isn’t clear, let’s break down that one-liner:
left_height = get_height(root.left)
right_height = get_height(root.right)
max_height = max(left_height, right_height)
return 1 + max_height
Since the function we’re calling always returns an integer, max is comparing two integers, which gives you the larger of the two integers. Which is something we can obviously add 1 to.
In other words, the height of the tree is 1 more than the height of whichever subtree is taller.
You may think I cheated there. How can I prove that the function always returns an integer, when I had to assume that to prove it?
The key is that recursion is inductive. If you don’t know much math, that’s a fancy way of saying this:
- If the base case always returns an integer,
- and recursion always calls a smaller case
- and if we always return an integer as long as all smaller cases return an integer
- then we always return an integer.
The first part is easy: if it’s None, we return 0.
The second part comes from the definition of a tree: the left branch of a tree and the right branch of a tree are always smaller subtrees of the tree. (This wouldn’t be true for a cyclic graph, where root.left could be root or its grandparent.)
The third part is the explanation from the first half of the answer.
And we’re done.
1for each level of the tree and returns the longest (max) route to a leaf (a node with no children).get_heightis independent. Thusrootis a binding unique for each one. The recursion is treated the same way as any other function and thus you call theget_heighton the left and right child nodes (which is whatrootgets to be for those) and you get the two heights of the subtrees except your node so you add 1 to the highest. I have no idea why you expect a type error.maxreturns a number andget_heightreturns a number (0for the root case, or1 + max(x, y)otherwise), why would that be aTypeError?