This website uses cookies to enhance the user experience

Find Lowest Common Ancestor in BST

Difficulty: 💪🏽 Medium

Problem Statement

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. The LCA is defined as the lowest node that has both nodes as descendants.

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

Input: root = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 4
Output: 2
Constraints
  • All values in the tree are unique.
  • p and q are different and both values exist in the BST.

Expected Challenge Output

When the function lowestCommonAncestor is called with the given example inputs, the expected outputs are:

  • For the input root = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 8, the output is 6.
  • For the input root = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 4, the output is 2.

let root = new TreeNode(6);
root.left = new TreeNode(2);
root.right = new TreeNode(8);
root.left.left = new TreeNode(0);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(7);
root.right.right = new TreeNode(9);
root.left.right.left = new TreeNode(3);
root.left.right.right = new TreeNode(5);
let p = root.left;
let q = root.right;
console.log(lowestCommonAncestor(root, p, q).val);  // Output: 6
p = root.left;
q = root.left.right;
console.log(lowestCommonAncestor(root, p, q).val);  // Output: 2
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}

function lowestCommonAncestor(root, p, q) {
// YOUR SOLUTION HERE
}

Memory: 0

CPU: 0