0
Binary Search Tree Iterative Insertion - Java
Hey, I tried making an iterative method to insert values to a Binary Search Tree. will this code work? public void iterInsert(int key){ Node current = this.root; while (current != null){ if (current.key > key) current = current.left; else if (current.key < key) current = current.right; else return; } current = new Node(key); }
1 ответ
0
I would say no, because in the end you create the node, you assign it to the local variable and the method terminates and the newly created node ends up being fed to the garbage collector. in practice you do not insert it in the structure but you run the structure and throw everything away.
you should stop when .right or .left is null. special case if the root is null. and assign the new node to one of the three