We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static class Node
{
public int data ;
public Node leftNode;
public Node rightNode;
public Node(int data)
{
this.data = data;
this.leftNode = null;
this.rightNode = null;
}
}
public static Node buildTree(Node root,int data)
{
if(root == null)
{
root = new Node(data);
return root;
}
if(root.data > data)
{
root.leftNode = buildTree(root.leftNode, data);
}
if(root.data<data)
{
root.rightNode = buildTree(root.rightNode, data);
}
return root;
}
public static Node lca(Node root,int a,int b)
{
if(root.data < a && root.data < b)
{
return lca(root.rightNode,a,b);
}
if(root.data > a && root.data > b)
{
return lca(root.leftNode,a,b);
}
return root;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc= new Scanner(System.in);
Node root = null;
int n = sc.nextInt();
int i=0;
while(i<n)
{
i++;
int inp = sc.nextInt();
root = buildTree(root, inp);
}
int a,b;
a=sc.nextInt();b=sc.nextInt();
Node lcaNode = lca(root, a, b);
System.out.println(lcaNode.data);
sc.close();
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Binary Search Tree : Lowest Common Ancestor
You are viewing a single comment's thread. Return to all comments →
**i got this answer from the youtube **
import java.io.; import java.util.*;
public class Solution {
}