Mon Apr 04, 2011 4:56 pm
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);
}
}
}
Wed May 30, 2012 7:14 pm
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.