Question presented to candidate: "Given the root of a binary tree, write a Python function that returns its maximum depth: the number of nodes on the longest path from the root down to a leaf. Start with whatever is simplest, then tell me what happens if the tree is a very long chain."
What a strong answer should cover:
- The recurrence
depth(None) = 0,depth(node) = 1 + max(depth(left), depth(right)), and that it is a postorder traversal. - O(n) time because every node is visited once; O(h) space for the call stack, which is O(n) for a chain.
- An iterative alternative: BFS counting levels with
collections.deque, or a stack of(node, depth)tuples. - Clarifying nodes versus edges and the empty-tree answer; awareness of the minimum-depth trap with one-child nodes.
- Python specifics: the default recursion limit of 1000 means a 1000-deep chain raises
RecursionError; usedeque.popleft()notlist.pop(0); tuple unpackingnode, d = stack.pop()keeps the stack version short.
Clarifying questions expected:
- "Is depth counted in nodes or edges, and what should an empty tree return?"
- "Could the tree be very deep, like a linked list?"
Code / implementation expected: Yes โ a recursive Python function, ideally followed by an iterative BFS or stack version.