Can someone convert the following code from java to scala? Please make sure it c
ID: 642593 • Letter: C
Question
Can someone convert the following code from java to scala? Please make sure it compiles before posting. Thanks.
import java.util.*;
public class Node
{
private int data;
private Node left,right;
public Node(int x)
{
this.left=null;
this.right=null;
this.data=x;
}
public void insert(int x)
{
if(x<this.data)
{
if(this.left==null)
this.left=new Node(x);
else
left.insert(x);
}
else if(x>this.data)
{
if(this.right==null)
this.right=new Node(x);
else
right.insert(x);
}
}
public boolean member(int x)
{
if(x<this.data) return this.left!=null?this.left.member(x):false;
if(x>this.data) return this.right!=null?this.right.member(x):false;
return true;
}
class Tree
{
Node root;
public Tree()
{
this.root=null;
}
public void insert(int x)
{
if(this.root==null)this.root=new Node(x);
else this.root.insert(x);
}
public boolean member(int x)
{
return this.root!=null?this.root.member(x):false;
}
}
public static void main(String[] args)
{
int x;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a value (or -1 to stop the loop)");
x=sc.nextInt();
Node n=new Node(x);
Tree t=n.new Tree();
while(x!=-1)
{
t.insert(x);
System.out.println("Enter a value (or -1 to stop the loop)");
x=sc.nextInt();
}
System.out.println("........Checking in the Tree..........");
System.out.println("Enter a value (or -1 to stop the loop)");
x=sc.nextInt();
while(x!=-1)
{
System.out.println(t.member(x));
System.out.println("Enter a value (or -1 to stop the loop)");
x=sc.nextInt();
}
}
}
Explanation / Answer
Tree.scala
Node.scala