/*************************************************************************** *Structure of the binary tree and the insert() method * *Binary trees are built like this, an item is compared to the current *node(starting at the top) if it less than the node, it goes to the left, *if it is greater it goes to the right. At the next level it is compared to *that node in the same fashion until it reaches a null node. * *for example, if this is our tree: * * 8 * / \ * 4 10 * *and we insert 5, it will be compared to 8. It is lesser so it goes to the left. *Then it is compared to 4, it is greater so it goes to the right where it stays *because it is a null node. Our tree then looks like this: * * 8 * / \ * 4 10 * \ * 5 * *Note that this is not a clear representation of the tree because we have *left out the null nodes, this is what it really looks like: * * 8 * / \ * 4 10 * / \ / \ * null 5 null null * / \ * null null * *The nulls are often left out of the map because they are assumed. * *So in our insert() method, we compare the new value to the current node, *starting at the top. If it is less, it gets passed to the left node, if the *left node is full, it gets passed deeper into the tree. * * ***************************************************************************/ public class BasicTree { int value; BasicTree left; BasicTree right; BasicTree(int v) { value = v; left = null; right = null; }//end BasicTree() { left = null; right = null; }//end public void insert(int v) { if(v < value) { if(left == null) { left = new BasicTree(v); } else { left.insert(v); } } else if(v > value) { if(right == null) { right = new BasicTree(v); } else { right.insert(v); } } }//end insert void printTree(int level){ if(left != null){ left.printTree(level + 1); } System.out.print(level+"-"+value+" "); if(right != null){ right.printTree(level + 1); } }//end printTree() /******* end methods *****************/ public static void main(String args[]){ BasicTree tree = new BasicTree(7); tree.insert(4); tree.insert(2); tree.insert(9); tree.printTree(0); }//end main }//end class