I have a binary tree that the root only has a left child. I am making methods to insert, delete and search the tree. My strategy is to make a temporary node called "current" and assign my root value to it at the start of each method. With this "current" node I traverse my tree looking for the correct spot to insert or delete nodes. My line of current = newNode
is what I thought would insert my newNode into the tree.
When I test to see if it works, I try to print root.leftChild.leftChild.name to see if it inserted, but it comes up null.
public void insertDate(String flight, String date) {
current = root.leftChild;
Node newNode = new Node(date);
while (current != null) {
if (current.name == flight) {
current = current.leftChild;
while (current != null) {
current = current.rightChild;
}
current = newNode;
return;
}
current = current.rightChild;
}
}
This code works here:
public void addFlight(String flight) {
current = root;
Node newNode = new Node(flight);
if (current.leftChild == null) {
current.leftChild = newNode;
System.out.println(flight + " has been added!");
} else {
current = current.leftChild;
while (current.rightChild != null) {
current = current.rightChild;
}
current.rightChild = newNode;
System.out.println(flight + " has been added!");
}
}