Question presented to candidate:
"You are given the root of a binary tree, a tree of Node objects with val, left and right. Write a Python function that returns true if the tree is height-balanced โ meaning that at every node, the heights of the left and right subtrees differ by at most one โ and false otherwise."
What a strong answer should cover:
- The definition applies at every node, not just the root, and an empty tree is balanced.
- The naive top-down approach (compute both heights at every node) and why it repeats work: O(n ยท h), so O(n log n) on a balanced tree.
- The bottom-up post-order approach: return the height, or a sentinel such as -1 as soon as a subtree fails, so the whole check is O(n).
- Space is the recursion stack, O(h): O(log n) when balanced, O(n) for a chain.
- Python details: compare the sentinel with
== -1(height 0 is falsy), and the default recursion limit of 1000 for skewed trees. - Why balance matters: search trees stay O(log n) only while their height is small.
Clarifying questions expected:
- Is "balanced" the height-gap-at-most-one definition, and is an empty tree balanced?
- Can the tree be very deep (risk of stack overflow)?
Code / implementation expected: Yes โ check_height(node) returning an int, plus is_balanced(root), in Python 3.