Print Common Nodes in BST Geeks solution
Problem :
Given two Binary Search Trees, task is to complete the function printCommon, which print's the common nodes in them. In other words, find intersection of two BSTs.
Solution : FInd inorder of both trees and save them in 2 arraylist and check with a loop for common elements
Code:
/*Complete the function below
Node is as follows:
class Node{
int data;
Node left,right;
Node (int d){
data=d;
left=right=null;
}
}
*/
class hackerranksolutionc
{
List<Integer> arr=new ArrayList<Integer>();
List<Integer>arr2=new ArrayList<Integer>();
public void inorder(Node root,boolean flag)
{
if(root==null)
return;
if(flag)
arr.add(root.data);
else
arr2.add(root.data);
inorder(root.left,flag);
inorder(root.right,flag);
}
public void printCommon(Node root1,Node root2)
{
inorder(root1,false);
inorder(root2,true);
Collections.sort(arr2);
for(int i=0;i<arr2.size();i++)
{
if(arr.contains(arr2.get(i)))
System.out.print(arr2.get(i)+" ");
}
}
}
Given two Binary Search Trees, task is to complete the function printCommon, which print's the common nodes in them. In other words, find intersection of two BSTs.
Solution : FInd inorder of both trees and save them in 2 arraylist and check with a loop for common elements
Code:
/*Complete the function below
Node is as follows:
class Node{
int data;
Node left,right;
Node (int d){
data=d;
left=right=null;
}
}
*/
class hackerranksolutionc
{
List<Integer> arr=new ArrayList<Integer>();
List<Integer>arr2=new ArrayList<Integer>();
public void inorder(Node root,boolean flag)
{
if(root==null)
return;
if(flag)
arr.add(root.data);
else
arr2.add(root.data);
inorder(root.left,flag);
inorder(root.right,flag);
}
public void printCommon(Node root1,Node root2)
{
inorder(root1,false);
inorder(root2,true);
Collections.sort(arr2);
for(int i=0;i<arr2.size();i++)
{
if(arr.contains(arr2.get(i)))
System.out.print(arr2.get(i)+" ");
}
}
}
0 Comments:
Post a Comment