I have a question regarding preorder traversal of binary search tree. I know what the algorithm has to be like, its pretty simple:
void preOrder(Node node) {
print(node);
if (node.left() != null)
preOrder(node.left());
if (node.right() != null)
preOrder(node.right());
}
For some reason, my function prints out only the left side subtree of the root node, and it prints out the lowest node twice. I ran a search method on one of the items on the right side and it returned true so I assume my insertion is working properly. Why is this happening?
My code is below. The public method calls the private one. In the private one, the first two if-statements are there to print the left and right nodes connected to that node. The last two do the actual recursive algorithm.
public void print() {
if (root == null)
System.out.println("Tree is empty");
else
print(root);
}
private void print(NodeBST node) {
printOut(node);
if (node.left() != null) {
System.out.print("Left: ");
printOut(node.left());
}
else
System.out.println("No left");
if (node.right() != null) {
System.out.print("Right: ");
printOut(node.right());
}
else
System.out.println("No right");
System.out.println("");
if (node.left() != null) {
node = node.left();
print(node);
}
if (node.right() != null) {
node = node.right();
print(node);
}
}
Well one bug you have is that you overwrite
nodeon the line just before the firstprint(node)and then reuse the modified version again straight afterwards. Presumably you wantnodeto be the original value when doing theif(node.right() != null)test?You can avoid this by e.g. just calling
print(node.left());in the firstif.