EDIT: I do not use any keys here because they would not work with my code - so my code is different from the one suggested.
I started working with binary trees last week at university, and we mostly use queues as a help when it comes to inserting anything to the tree. But i was wondering if it would be possible to do it without the help of the queue. I made this code so far:
public void withoutQueue(Node newNode) {
if (root == null) {
root = newNode;
current = root;
} else if (root != null) {
if (current.left == null) {
current.left = newNode;
newNode.parent = current;
counterleft++;
} else if (current.left != null && current.right == null) {
current.right = newNode;
newNode.parent = current;
counterright++;
} else if (current.left != null && current.right != null && current.left.left == null && counterleft <= counterright) {
Node helper = current;
current = current.left;
current.parent = helper;
counterleft++;
breadthFirstAppend(newNode);
} else if (current.left != null && current.right != null && counterright <= counterleft) {
Node helper = current;
current = current.parent.right;
current.parent = helper;
counterright++;
breadthFirstAppend(newNode);
}
}
}
But this far it does not really work that good. It inserts the first three correctly (root, root.left, root.right) - but then jumps to the 6th inserted node... i simply dont know what to do at this point. I added the counterleft/right integers so that i could maybe control it via that, but it didnt help very much.
My core problem is that it either jumps down only on the left (1,2,4,..) or only on the right (1,3,5,...) - but it should jump (1,2,3,4,5,...).
Any tips for how i could improve this code? I'll update it when I find something out myself.