Finding the common ancestor in a binary search tree in Javascript is not rocket science. However, many a time, newbies struggle in understanding how the values flow within the recursive calls. This post will help you understand the steps, and output involved at each stage of the algorithm.

Let’s get started.

The Tree

Here is a simple, binary search tree upon which the common ancestor algorithm ought to be executed.

Image for post

Binary Search Tree for finding the Lowest Common Ancestor (LCA)

We are going to find the common ancestor, for three different cases [5,50] [1,2] and [1,5].

Algorithm

The algorithm used to identify the Lowest Common Ancestor is:

lowestCommonAncestor(root, p, q) {
    if (root == null) return null;
    if (root.value == p || root.value == q) return root;
    let leftNode = this.lowestCommonAncestor(root.left, p, q);
    let rightNode = this.lowestCommonAncestor(root.right, p, q);
    if (leftNode && rightNode) return root;
    if (!leftNode && !rightNode) return null;
    return leftNode ? leftNode : rightNode;
}

Exit Conditions

Condition 1: If both leftNode and rightNode are populated, the root is returned as the LCA.

Condition 2: If both the leftNode and rightNode are null, then the function returns null.

Condition 3: If either the leftNode or the rightNode is populated, the function returns the populated value.

#interview-questions #binary-search-tree #optimization #lowest-common-ancesto #javascript #programming

Finding Common Ancestor, Binary Search Tree, JavaScript
10.20 GEEK