I am trying to print a binary search tree and get the following output:
-19->4->5->6->259->
How do I adjust the traverse function so that the last arrow is not printed in the output?
I am using this code inside the main function:
Tree x = new Tree(5);
x.add(6);
x.add(4);
x.add(259);
x.add(-19);
x.traverse(x);
The Tree class is below:
public class Tree {
Tree root;
Tree left;
Tree right;
int value;
public Tree(int value){
this.value=value;
this.left=null;
this.right=null;
}
boolean add(int value){
if (value == this.value)
return false;
else if (value <this.value) {
if (left == null) {
left = new Tree(value);
return true;
} else
return left.add(value);
} else if (value > this.value) {
if (right == null) {
right = new Tree(value);
return true;
} else
return right.add(value);
}
return false;
}
void traverse(Tree root){
if (root.left != null){
traverse(root.left);
}
System.out.printf("%d",root.value);
System.out.printf("->");
if (root.right != null){
traverse(root.right);
}
}
}