Reputation: 317
Today I am trying to loop a print statement so it outputs different results each time. The premise is I have a binary search tree that has been filled with random numbers 0-99.
I then select a random node and get the length from root to this random node.
I need to repeat the above sentence a number of times but all my loops so far have given the same answer or looped infinitely.
while(i!=10){
System.out.println(bst.Pathlength(root, random_node));
i++;
}
for (int i = 0;i< 10; i++){
System.out.println(bst.Pathlength(root, random_node));
}
while (true) {
int i = 0;
int j = 1000;
if (i != j) {
System.out.println(bst.Pathlength(root, random_node));
i++;
}else if (i == j){
break;
}
}
Above is a selection of loops I have been trying(not at the same time). Pastebin link with full program Included full program for the full picture.
Any pointers on this would be great :)
Upvotes: 1
Views: 122
Reputation: 56499
Currently, you're passing in the same instance at each iteration of the loops hence why it will print the same result each time as you've mentioned, rather you'll need to traverse all the nodes within the tree meaning from the current node, then left(if any), then right(if any).... and so forth down the tree.
you might want to create an inOrder
method which traverses down the tree to print the data of the sub-trees.
As for you loops, the first two should work as expected, However, the last loop will always loop infinitely because you're resetting i
to 0
at each iteration of the loop, meaning it will never reach j
in order to break out of the loop. Solution to this is simply to declare the i
and j
variables outside the loop.
Different types of Tree Traversals
.
Upvotes: 2