I am trying to implement binary search tree. One method which I am trying to implement in the most efficient and stylish way is node insertion.
I am under the impression that while (true) is a bad practice, correct?
while (true){ if(n <currentNode.data){ if (currentNode.left == null){ currentNode.left = new node(n); break; }else{ currentNode = currentNode.left; } }else if (currentNode.right == null) { currentNode.right = new node(n); break; } else{ currentNode = currentNode.right; } }
and here is the whole code:
package graph; public class BSearchTree { private node head = null; public BSearchTree(int [] entries){ for (int a : entries){ insert(a); } } public void insert(int n){ if (head == null){ head = new node(n); return; } node currentNode = head; while (true){ if(n <currentNode.data){ if (currentNode.left == null){ currentNode.left = new node(n); break; }else{ currentNode = currentNode.left; } }else if (currentNode.right == null) { currentNode.right = new node(n); break; } else{ currentNode = currentNode.right; } } } public static void main(String[] args) { BSearchTree bst = new BSearchTree(new int[]{2,4,1,5}); System.out.println(bst.toString()); } private class node { int data = -1; node left = null; node right = null; public node(int n){ data = n; } } }