Lowest Common Ancestor of Deepest Leaves

MediumTreestree dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a non-empty binary tree with distinct values, consider the nodes at the **maximum depth** (the deepest leaves). Find their lowest common ancestor: the deepest node whose subtree contains every one of them. If there is only one deepest node, it is its own ancestor. Return that node; the grader serializes the **subtree rooted at it** in level order. A single post-order pass that returns (depth, candidate) pairs runs in O(n).

Examples

Input: root = [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
The deepest nodes are 7 and 4; their lowest common ancestor is 2.
Input: root = [1]
Output: [1]
The root is the only node and the only deepest leaf.
Input: root = [0,1,3,null,2]
Output: [2]
Node 2 alone is the deepest, so the answer is node 2 itself.

Constraints

  • 1 <= number of nodes <= 1000
  • 0 <= Node.val <= 1000
  • All values are distinct

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More tree dp problems