• Post Reply Bookmark Topic Watch Topic
  • New Topic

difficulty with binary searches  RSS feed

 
Jim Standish
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm having difficulty calling my inOrder method. The only thing that
shows is the root. I'm not absolutely sure if the data from my array
even got inserted, so I'll show you what I did to insert as well.

////////here's how I called *.inOrder(Node) from my main method://////////
Node node = new Node();
node = treeThreeData[0]
tree3.inOrder( node ); //The array is what was inserted
// previously to build the tree.

////////////here's the method I'm trying to call in my Tree class://////
public void inOrder ( Node aNode )
{
if (aNode != null)
{
inOrder (aNode.lChild);
aNode.display();
inOrder (aNode.rChild);
}
}

////////////here's the way I inserted:///////////////////
int[] treeThreeData = { 45,55,57,59,60,67,100,101,107 };
for( int i = 0 ; i <= treeThreeData.length - 1 ; i++ )
{
tree3.insert( treeThreeData[i] );
}

///////////////*.insert calls this method in my Tree class://///////////
public void insert (int val)
{
Node newNode = new Node (val);

if (root == null) //If no nodes in tree yet...
{
root = newNode;
}
else
{
Node current = root;
Node parent = root;
while (current != null)
{
parent = current;
if (val < current.iData)
current = current.lChild;
else
current = current.rChild;
}
if (val < parent.iData)
parent.lChild = newNode;
else
parent.rChild = newNode;
}
}
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried to do the add recursively?
 
Jim Standish
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you mean putting my original data arrays in as arguments? Or did you have something else in mind? -J.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What I mean is that a binary search tree works well with recursion. You have successfully created the method which recursively traverses the tree.

It might be easier to try to use the same logic to add to the tree.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!