FunctionRacerProblemsRace

Lowest Common Ancestor of a BST

EasyTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. The lowest common ancestor of two values p and q is the deepest node that has both of them in its subtree (a node counts as being in its own subtree). Return the value of that node. Both p and q are in the tree and are different. In a binary search tree every value in a left subtree is smaller than its node and every value in a right subtree is larger.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [6,2,8,0,4,7,9,null,null,3,5]
p 2
q 8
returns 6

2 and 8 split at the root, 6.

Example 2

root [6,2,8,0,4,7,9,null,null,3,5]
p 2
q 4
returns 2

4 is below 2, so the answer is 2.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems