In the following insert method for a binary search tree (BST), the left side of the tree is being updated correctly, but there is an issue with inserting values on the right side. Despite using the debugger to check the output, the method adds some values incorrectly to both the left and right sides. Can someone help identify and fix the issue?
This got me confused as it is my first time exercise on a binary search tree
question
//here is the code
public void insert(int number) {
Node newNode = new Node(number);
if (isEmpty()) {
root = newNode;
}
Node current = root;
Node parent;
while (true) {
parent = current;
if (current.data > number) {
current = current.left;
if (current == null){
parent.left = newNode;
return;
}
}
else{
current = current.right;
if(current == null){
parent.right = newNode;
return;
}
}
}
}
Ezana is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.