Question: code from A: public class BinarySearchTree { private TreeItem root; public BinarySearchTree ( ) { root = null; } public boolean insert ( String value

code from A:
public class BinarySearchTree {
private TreeItem root;
public BinarySearchTree(){
root = null;
}
public boolean insert(String value){
if(root == null)
root = new TreeItem(value);
else{
TreeItem parent = null;
TreeItem current = root;
while(current != null){
if(value.compareTo(current.getValue())==0)
return false;
else if(value.compareTo(current.getValue())0){
parent = current;
current = current.left;
}
else {
parent = current;
current = current.right;
}
}
if(value.compareTo(current.getValue())>0)
parent.left = new TreeItem(value);
else
parent.right = new TreeItem(value);
}
return true;
}
public boolean search(int value){
TreeItem curr = root;
while(curr != null)
{
if(curr.getValue()== value)
return true;
else if(curr.getValue()> value)
curr = curr.left;
else
curr = curr.right;
}
return false;
}
private void inorder(TreeItem root){
if(root!=null){
inorder(root.left);
System.out.print (root);
inorder(root.right);
}
}
public void inorder(){
inorder(root);
System.out.println ();
}
}
public class TreeItem {
TreeItem left;
TreeItem right;
int value;
public TreeItem(int value){
left = null;
right = null;
this.value = value;
}
public int getValue(){
return value;
}
public String toString(){
if(left != null && right != null)
return value +"- have both children
";
else if(left != null)
return value +"- have left child
";
else if(right != null)
return value +"- have right child
";
else
return value +"- have no children
";
}
}
InputFile:
red
green
blue
yellow
orange
purple
indigo
pink
lime
white
black
brown
magenta

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!