Lowest Common Ancestor of a Binary Search Tree
Try to solve the Lowest Common Ancestor of a Binary Search Tree problem.
We'll cover the following
Statement#
Given a binary search tree with 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:
-
Node.data - All
Node.dataare unique. node1node2node1andnode2exist in the tree.
Examples#
1 of 3
2 of 3
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
What is the lowest common ancestor of and in the following binary search tree?
5
/ \
4 8
/ \
7 9
5
4
9
8
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.
Try it yourself#
Implement your solution in the following coding playground.
Solution: Build Binary Tree from Preorder and Inorder Traversal
Solution: Lowest Common Ancestor of a Binary Search Tree