Skip to interview prep
Apexed

58. Lowest Common Ancestor in a BST

MediumTrees

Given a BST and two values p and q present in it, return the value of their lowest common ancestor.

A binary tree is passed as TreeNode objects with val, left and right. The tests write trees in level order, with null for a missing child.

Example 1

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

Constraints

  • p and q exist in the tree

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 4 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Lowest Common Ancestor in a BST — coding interview practice — Apexed