×

Lowest common ancestor in a binary search tree

Suppose you have given two values of nodes in a binary search tree. You have to find out the lowest common ancestor between the nodes.

Let’s take an example tree-

Binary Tree

For the above binary search tree, if we take inputs 3 and 5, then the output will be 4. It is supposed that there will be a particular output for every input.

Input- 0, 4

Output- 2

Explanation- 0 and 4 both nodes are in the lower level of 2. 2 is the closest node of both nodes, so it is the lowest common ancestor.

Note: -

What is the lowest common ancestor in a binary search tree?

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes m and n as the lowest node in T that has both m and n as descendants (where we allow a node to be a descendant of itself ).”

Algorithm:-

Step 1: Start

Step 2: Two values are taken from the user

Step 3: A tree is created

Step 4: A recursive function called. This function takes two input values and one tree node.

Step 5: If the values are less than the node value, the function is again called with the left node.

Step 6: If the values are greater than the node value, the function is called with the right node.

Step 7: If steps 5 and 6 are not satisfying, then the node value will be returned.

Step 8: The returned value will be printed.

Step 9: Stop.

Explanation of Algorithm: We take the above-given tree, and inputs are 0 and 5. If we call the recursive function with the root node and values, then the function is again called with the node's left node because 0 and 5 are both less than 6. After that, values are compared with node's value two, and here we get our answer because 0 is less than 2, but 5 is greater than 2. The function will return 2.

Code

#include <bits/stdc++.h>
using namespace std;
class node
{
	public:
	int value;
	node* left, *right;
};
/* Function to find LCA of m and n.
The function assumes that both
m and n are present in BST */
node *fun(node* root, int m, int n)
{
	if (root == NULL) 
                return NULL;
	// If both m and n are smaller
	// than root, then LCA lies in left
	if (root->value > m && root->value > n)
		return fun(root->left, m, n);
	// If both m and n are greater than
	// root, then LCA lies in right
	if (root->value < m && root->value < n)
		return fun(root->right, n1, n2);
	return root;
}
/* Helper function that allocates
a new node with the given data.*/
node* insert(int data)
{
	node* root = new node();
	root->value = data;
	root->left = root->right = NULL;
	return(root);
}
/* Driver code*/
int main()
{
	// Let us construct the BST
	// shown in the above figure
	node *root = insert(6);
	root->left = insert(2);
	root->right = insert(8);
	root->left->left = insert(0);
	root->left->right = insert(4);
            root->right->left = insert(7);
	root->right->right = insert(9);
	root->left->right->left = insert(3);
	root->left->right->right = insert(5);
	int m = 0, n = 4;
	node *t = fun(root, m, n);
	cout << "LCA of " << m << " and " << n << " is " << t->value<<endl;
	m = 4, n = 7;
	t = fun(root, n1, n2);
	cout<<"LCA of " << m << " and " << n << " is " << t->value << endl;
	m = 0, n = 2;
	t = fun(root, m, n);
	cout << "LCA of " << m << " and " << n << " is " << t->value << endl;
	return 0;
}

Output

LCA of 0 and 4 is 2
LCA of 4 and 7 is 6
LCA of 0 and 2 is 2

Complexity Analysis

Time complexity- Here, the recursion continues till we find the LCA. So, the complexity directly depends on the height of the tree. Complexity will be O(h).

Space complexity- In this recursive solution, we use constant memory. So, space complexity will be O(1).

Note- The above code and algorithm are based on a recursive approach. The main drawback of this solution is for recursion purposes, and we have to allocate the memory of the function stack. But if we use an iterative approach, then we can avoid this problem. In the iterative solution, we will use the loop in the main function. The loop will continue till we get the answer. The root is updated in every iteration by the left node or right node according to steps 5, 6, and 7 of the algorithm.


Related Topics

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Identical Linked Lists

Identical Linked Lists In this problem, we have given two linked lists, and we need to check whether the given linked lists are identical or not. Identical means they have the...

4 minutes read.

Interval Tree

Interval Tree Interval Tree: The concept is to increase a Binary Search Tree self-balancing such as Red Black Tree, and AVL Tree, so that every feature can be completed in time O(Logn). Each Interval...

4 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Finding Rank in a Binary Search Tree

Implementation // writing a C++ program to find out the rank and element in the program.  #include <bits/stdc++.h> using namespace std; struct __nod { int record; __nod *Lft, *Rt; int LftSize; }; __nod* new__nod(int record) { __nod *temp = new __nod; temp->record...

6 minutes read.

All About Minimum Cost Spanning Trees in Data Structure

Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system that stores, manages, and optimizes...

7 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Rotate a Singly Linked List

Rotate a Singly Linked List This article will explain how we can rotate the singly linked list. Here we have given a singly linked list, and we need to rotate this...

4 minutes read.

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method. What is recursion? Defining anything in terms...

7 minutes read.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.

Flatten Binary Tree to a linked list

Implementation In this section, we will see the implementation of the binary Tree and its conversion into linked lists. let us proceed: - // Writing a C++ program that will convert a...

4 minutes read.

Difference between B-tree and Binary Tree

What is B-TREE? The nodes of B-tree are sorted during in-order traversal, and it is called self-balancing tree. A node in a B-tree can have more than two offspring, in contrast...

3 minutes read.

Hashing

Hashing: Hashing is a process in which a large amount of data is mapped to a small table with the help of hashing function. It is a searching technique. Hash table We...

4 minutes read.

Linear Queue Data Structure in C

Data Structure There are many ways to store data in programming, that Queue has features that make it all the more special. We all know that data structure is a way...

9 minutes read.

Properties of Binary Tree

Trees are maybe of the most significant datum structures. They are used to store and figure out data. A binarytree is a tree data structure made from nodes, all of which has...

3 minutes read.

Red Black Tree vs AVL Tree: Data Structure

Difference Between Red Black Tree vs AVL Tree Red Black Tree: A red-black tree is referred as self-balancing binary search tree. In red-black, each node stores an extra bit that determines...

4 minutes read.

Arrange consonants and vowels nodes in a linked list

Arrange consonants and vowels nodes in a linked list In this problem, we have given a singly linked list. Here we will arrange the consonants and vowels nodes of the list...

2 minutes read.

Stack Data Structure

The stack is a non-primitive and linear data structure. It works on the principle of LIFO (Last In First Out). That is, the element that is added to the end...

3 minutes read.

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

3 minutes read.