Binary Search Tree : Lowest Common Ancestor


Problem Statement :


You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1  and v2  in the binary search tree.

In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes  and  as descendants.

Function Description

Complete the function lca in the editor below. It should return a pointer to the lowest common ancestor node of the two values given.

lca has the following parameters:
- root: a pointer to the root node of a binary search tree
- v1: a node.data value
- v2: a node.data value

Input Format

The first line contains an integer, n , the number of nodes in the tree.
The second line contains n  space-separated integers representing node.data values.
The third line contains two space-separated integers, v1 and v2 .

To use the test data, you will have to create the binary search tree yourself. Here on the platform, the tree will be created for you.


The tree will contain nodes with data equal to v1 and v2.

Output Format

Return the a pointer to the node that is the lowest common ancestor of  and .



Solution :



title-img


                            Solution in C :

In C++ :




/*
Node is defined as 

typedef struct node
{
   int data;
   node * left;
   node * right;
}node;

*/
bool isPresent(struct node* tree, int k)
{
	if(tree==NULL)
		return false;
	if(tree->data==k)
		return true;
	return isPresent(tree->left,k) || isPresent(tree->right,k);
}


node * lca(node * tree, int m,int n)
{
    
	if(tree==NULL)
		return NULL;
	if(tree->data>m && tree->data>n)
		return lca(tree->left,m,n);
	if(tree->data<m && tree->data<n)
		return lca(tree->right,m,n);
	if(tree->data<m && tree->data>n)
	{
		if(isPresent(tree->left,n) && isPresent(tree->right,m))
		{
			return tree;
		}
		else 
			return NULL;
	}
	if(tree->data>m && tree->data<n)
	{
		if(isPresent(tree->left,m) && isPresent(tree->right,n))
		{
			return tree;
		}
		else 
			return NULL;
	}
	if(tree->data==m)
	{
		if(tree->data<n)
		{
			if(isPresent(tree->right,n))
				return tree;
			else
				return NULL;
		}
		if(tree->data>n)
		{
			if(isPresent(tree->left,n))
				return tree;
			else
				return NULL;
		}
		if(tree->data==n)
			return tree;
	}
	if(tree->data==n)
	{
		if(tree->data<m)
		{
			if(isPresent(tree->right,m))
				return tree;
			else
				return NULL;
		}
		if(tree->data>m)
		{
			if(isPresent(tree->left,m))
				return tree;
			else
				return NULL;
		}
		if(tree->data==m)
			return tree;
	}

    
	return NULL;
	
}


   



In Java :





 /* Node is defined as :
 class Node 
    int data;
    Node left;
    Node right;
    
    */

static Node lca(Node root,int v1,int v2)
    {
        Queue<String> v1path = new LinkedList<String>();
        Queue<String> v2path = new LinkedList<String>();
        String left = "l";
        String right = "r";
        Node rootcopy1 = new Node();
        rootcopy1 = root;
        Node rootcopy2 = new Node();
        rootcopy2 = root;
    
        while(rootcopy1 != null) //finding v1's path
            {
                if(v1 == rootcopy1.data) //found it, no need to continue
                    {
                        break;
                }
                else if(v1 < rootcopy1.data)
                    {
                        v1path.add(left);
                        rootcopy1 = rootcopy1.left;
                }
                else
                    {
                        v1path.add(right);
                        rootcopy1 = rootcopy1.right;
                }
        }
    
        while(rootcopy2 != null) //finding v2's path
            {
                if(v2 == rootcopy2.data) //found it, no need to continue
                    {
                        break;
                }
                else if(v2 < rootcopy2.data)
                    {
                        v2path.add(left);
                        rootcopy2 = rootcopy2.left;
                }
                else
                    {
                        v2path.add(right);
                        rootcopy2 = rootcopy2.right;
                }
        }
    
        rootcopy1 = root; //need to travel along tree down from root again to find LCA to return
    
        while(v1path.peek() != null && v2path.peek() != null) //comparing paths taken to find v1 and v2 to determine LCA
            {
                if(v1path.peek() == v2path.peek()) //if paths take same branch, LCA is farther down from here, keep going
                    {
                        if(v1path.peek() == "l") //take left
                            {
                                v1path.remove();
                                v2path.remove();
                                rootcopy1 = rootcopy1.left;
                        }
                        else //take right
                            {
                                v1path.remove();
                                v2path.remove();
                                rootcopy1 = rootcopy1.right;
                        }
                }
                else //this is the LCA since the paths split here
                    {
                        break;
                }
        }
        return rootcopy1;
    }






In python3 :



# Enter your code here. Read input from STDIN. Print output to STDOUT
'''
class Node:
      def __init__(self,info): 
          self.info = info  
          self.left = None  
          self.right = None 
           

       // this is a node of the tree , which contains info as data, left , right
'''

def lca(root, v1, v2):
    node=root
    if node is None:
        return None
    if node.info>v1 and node.info>v2:
        return lca(node.left,v1,v2)
    elif node.info<v1 and node.info < v2:
        return lca(node.right,v1,v2)
    else:
        return node





In C :




/* you only have to complete the function given below.  
node is defined as  

struct node {
    
    int data;
    struct node *left;
    struct node *right;
  
};

*/
struct node *lca( struct node *root, int v1, int v2 ) {
if( root->data == v1 || root->data == v2 )
            return root;
        if( root->data > v1 && root->data > v2 )
            return lca(root->left, v1, v2);
        if( root->data < v1 && root->data < v2 )
            return lca(root->right, v1, v2);
        return root;
}
                        








View More Similar Problems

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →