Lowest Common Ancestor of a Binary Search Tree Visualizer & Step-by-Step Algorithm Solution

Find the lowest common ancestor (LCA) node of two given nodes p and q in a Binary Search Tree (BST) using value comparisons.

Category: trees | Difficulty: Medium

Tags: BST, Binary Search Tree, DFS, Tree Traversal, Ancestor

Lowest Common Ancestor of a Binary Search Tree

6
2
0
4
3
5
8
7
9
100%
state
p2
q8
currnull
Initialization
1/3
Explanation

Start lowestCommonAncestor for target nodes p = 2 and q = 8.

Source Code
1function lowestCommonAncestor(root, p, q) {
2 let curr = root;
3 while (curr) {
4 if (p.val < curr.val && q.val < curr.val) {
5 curr = curr.left;
6 } else if (p.val > curr.val && q.val > curr.val) {
7 curr = curr.right;
8 } else {
9 return curr;
10 }
11 }
12 return null;
13}