CodeOath
← All problems

Lowest Common Ancestor of a BST

Medium
treesbinary-search-tree

Given the root of a binary search tree, and the values of two nodes pVal and qVal that exist in the tree, return the value of their lowest common ancestor (LCA) — the deepest node that has both as descendants (a node can be a descendant of itself).

To keep this simple across languages, pVal/qVal are passed as plain integers (the target values) rather than node references, and the answer is returned as the LCA node's value.

Trees in this problem are given as a level-order array: null marks a missing child, and trailing nulls are omitted.

Example:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], pVal = 2, qVal = 8
Output: 6