Lowest Common Ancestor of a Binary Search Tree

Try to solve the Lowest Common Ancestor of a Binary Search Tree problem.

Statement#

Given a binary search tree with nn nodes, your task is to find the lowest common ancestor of two of its nodes, node1 and node2.

The lowest common ancestor of two nodes, node1 and node2, is defined as the lowest node in the binary search tree that has both node1 and node2 as descendants.

By definition, a node is a descendant of itself. For example, if node2 is a descendant of node1, and we know that node1 is a descendant of itself, then node1 will be the lowest common ancestor of node1 and node2.

Constraints:

  • 2n5002 \leq n \leq 500
  • 103-10^3 \leq Node.data 103\leq 10^3
  • All Node.data are unique.
  • node1 \neq node2
  • node1 and node2 exist in the tree.

Examples#

canvasAnimation-image

1 of 3

canvasAnimation-image

2 of 3

canvasAnimation-image

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Lowest Common Ancestor of a Binary Search Tree

1

What is the lowest common ancestor of 44 and 77 in the following binary search tree?

  5
 / \
4   8
   / \
  7   9
A)

5

B)

4

C)

9

D)

8

Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding on how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Start traversing from the root of the binary search tree.

Compare the values of node1 and node2 with the current node’s value.

If both values are greater, move to the right child. If both values are smaller, move to the left child.

Otherwise, if the current node’s value is between the values of node1 and node2, return the current node as the lowest common ancestor.

Continue the traversal until the LCA is found.


Try it yourself#

Implement your solution in the following coding playground.

Python
usercode > LowestCommonAncestor.py
Input #1
Input #2
Input #3
Lowest Common Ancestor of a Binary Search Tree

Solution: Build Binary Tree from Preorder and Inorder Traversal

Solution: Lowest Common Ancestor of a Binary Search Tree