Joined: Tue Mar 27, 2007 10:55 pm Posts: 2277 Location: Earth Has thanked: 39 time Have thanks: 61 time
Java Binary Tree example
Code:
public class BinaryTree {
static class TreeNode {
TreeNode leftReference; TreeNode rightReference; int nodeValue;
public TreeNode(int nodeValue){ this.nodeValue = nodeValue; } }
public static void main(String[] args){ new BinaryTree().run(); }
public void run(){ // tree root node. int rootValue = 40; TreeNode rootnode = new TreeNode(rootValue); System.out.println("root node created. "+ rootnode.nodeValue);
// insertNode new element starting with rootnode. insertNode(rootnode, 11); insertNode(rootnode, 15); insertNode(rootnode, 16); insertNode(rootnode, 23); insertNode(rootnode, 79); System.out.println("print the content of tree in binary tree order");
printTree(rootnode);
}
/* * * inserting new parentNode to tree. * binary tree set the smaller nodeValue on left and the bigger nodeValue on the right * parent TreeNode in the first case will be root node. */ public void insertNode(TreeNode parentNode, int nodeValue){ if (nodeValue < parentNode.nodeValue){ if (parentNode.leftReference != null){ // Go more depth to left. insertNode(parentNode.leftReference, nodeValue); } else { System.out.println(" LEFT: new node value "+ nodeValue +" , its root "+ parentNode.nodeValue); parentNode.leftReference = new TreeNode(nodeValue); } } else if (nodeValue > parentNode.nodeValue){ if (parentNode.rightReference != null){ // Go more depth to right insertNode(parentNode.rightReference, nodeValue); } else { System.out.println(" Right: new node value "+ nodeValue +", its root "+ parentNode.nodeValue); parentNode.rightReference = new TreeNode(nodeValue); } } }
/* * * recursivly printing the content of the tree. */ public void printTree(TreeNode node){ if (node != null){ printTree(node.leftReference); System.out.println(" node value "+ node.nodeValue); printTree(node.rightReference); } } }
_________________ Currenlty programming with : java , html , php , and javascript . (OCJP-6 certified )