© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu
Quick Links
Easy Studies

Creating Binary Tree Using Java

Description:

Binary Tree is the specialized tree that has two possible branches i.e. left and right branch. These tree are useful when you build a parse of tree especially in mathematics and Boolean. The java binary tree finds its application in games. Binary Tree is basic concept of data structure. In this program inside the main method we instantiate Binary Tree Example class to a memory, that call run ( ) method. Inside this class we have a static node class and have two static node variable Node left, Node right and int value to store the respective node value. The Node constructor creates a node object that accepts a node value as argument that can be object or reference. The run method ( ) create an instance of node class start with node value of 25. The System.out.println prints the value of the node by calling rootnode.value. The rootnode.value return you the value of the node.

In the same way you insert the different value in the node using insert ( ) method. The insert method accepts a node and int as argument value. The conditional operator is used to evaluate the position of various nodes, if the value of the node is less than the root node then, the system.out.println print the value of node to the left of root node, Incase the value of node is greater than root node, and the println print the node value to the right of it.

Creating Binary Tree Using Java :

public class BinaryTreeExample { public static void main(String[] args) { new BinaryTreeExample().run(); } static class Node { Node left; Node right; int value; public Node(int value) { this.value = value; } } public void run() { Node rootnode = new Node(25); System.out.println("Building tree with rootvalue " + rootnode.value); insert(rootnode, 12); insert(rootnode, 10); insert(rootnode, 16); insert(rootnode, 13); insert(rootnode, 79); System.out.println("Traversing tree in order"); System.out.println("================================="); printInOrder(rootnode); } public void insert(Node node, int value) { if (value < node.value) { if (node.left != null) { insert(node.left, value); } else { System.out.println(" Inserted " + value + " to left of node " + node.value); node.left = new Node(value); } } else if (value > node.value) { if (node.right != null) { insert(node.right, value); } else { System.out.println(" Inserted " + value + "to right of node " + node.value); node.right = new Node(value); } } } public void printInOrder(Node node) { if (node != null) { printInOrder(node.left); System.out.println(" Traversed " + node.value); printInOrder(node.right); } } }

 
SLogix Student Projects

⇓Student Projects⇓
⇑Student Projects⇑
bottom