Lowest Common Ancestor of a Binary Tree
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 neededProblem
Given the root of a binary tree and the values p and q of two different nodes in it, return the value of their **lowest common ancestor**.
The lowest common ancestor is the deepest node that has both p and q among its descendants, where a node counts as a descendant of itself. So if one of the two nodes lies inside the other's subtree, the upper node is the answer.
All values in the tree are distinct, and both p and q are guaranteed to be present. The tree is an ordinary binary tree, not a binary search tree.
Examples
Constraints
- 2 <= number of nodes <= 10^5
- -10^9 <= Node.val <= 10^9
- All values are distinct
- p != q
- `p` and `q` are values of nodes in the tree
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.