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.

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.

Constraints


1   <=   n,  node.data  <= 25
1   <=  v1, v2  <= 25
v1  =/  v2 

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  v1 and v2.



Solution :



title-img


                            Solution in C :

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;
}
                        


                        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;
	
}
                    


                        Solution in Java :

In   Java   :







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

static Node lca(Node root,int v1,int v2)
    {
        int min=Math.min(v1,v2);
        int max=Math.max(v1,v2);
        if(root.data>=min && root.data<=max){
            return root;
        }else if(root.data>max && root.data>max){
            return lca(root.left,v1,v2);
        }else{
            return lca(root.right,v1,v2);
        }
       
    }
                    


                        Solution in Python : 
                            
In  Python3 :






'''
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
                    


View More Similar Problems

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →