6_1
There are four leaves, 3 nodes have two children, and it would take 2 iterations to find out that 12 is not in it, i believe
6_2
Yes it worked.
6_3
I don't know why it took me so long to figure out where to put the code
public void add(Object newValue)
{
TreeNode newNode = new TreeNode(newValue,null,null);
if(root==null)//bst is empty, make root reference node referenced by newNode
{
root=newNode;
}//if
else//search for place to insert node referenced by newNode
{
TreeNode T=root;//T is a traversing TreeNode reference (pointer)
TreeNode follow=null;//follows one node behind T
while(T!=null)
{
follow=T;
if (((Comparable)newNode.getValue()).compareTo(T.getValue())==0){return;}
if (((Comparable)newNode.getValue()).compareTo(T.getValue())>0)
{//the value in node referenced by newNode >=
//value in node referenced by T (go right)
T=T.getRight();
}//if
else
{//go left
T=T.getLeft();
}//else
}//while
//follow will now reference (point to) the node where insertion to be made
if (((Comparable)newNode.getValue()).compareTo(follow.getValue())>=0)
{//the value in node referenced by newNode >=
//value in node referenced by follow (link right)
follow.setRight(newNode);
}//if
else
{//link left
follow.setLeft(newNode);
}//else
}//else
}//add
}//class BST
6_4
I am not sure why
6_5
public void find(Object target){
if(root==null){return;}
TreeNode T=root;//T is a traversing TreeNode reference (pointer)
TreeNode follow=null;//follows one node behind T
while(T!=null); {
follow = T;
if (((Comparable)newNode.getValue()).compareTo(T.getValue())==0) {return T;}
if (((Comparable)newNode.getValue()).compareTo(T.getValue())>0) {T=T.getRight();}
else {T=T.getLeft();}
}
return null;
}
אין תגובות:
הוסף רשומת תגובה