TREE EXAMPLE PROGRAM IN JAVA

 class Node  
 {  
      int data;   
      Node left;  
      Node right;  
      Node(int d)   
           {  
                data =d;   
                left=null;  
                right=null;   
           }  
 }  
 /*======================================================================*/  
 class Tree  
 {  
 private Node root;  
      Tree()  
      {  
      root=null;   
      }   
 public Node getRoot()  
      {  
           return root;   
      }  
 public void insert(int data)  
      {  
           Node node = new Node(data);  
           if(root==null)  
                {  
                root=node;   
                }  
           else   
                {  
                Node current = root;  
                Node parent;   
                     while(true)  
                     {  
                     parent = current;   
                     if(current.data>data)  
                          {  
                          current=current.left;  
                          if(current==null){  
                               parent.left = node;   
                               return;}  
                          }//if   
                      else  
                          {  
                          current=current.right;  
                          if(current==null){  
                               parent.right = node;  
                               return;}  
                          }//end of else   
                     }// end of whild loop   
                }  
      }  
 public void inOrder(Node localRoot)  
      {  
           if(localRoot != null)  
           {  
                inOrder(localRoot.left);  
                System.out.println(localRoot.data);  
                inOrder(localRoot.right);  
           }  
      }  
 }  
 /*======================================================================*/  
 class TreeApp  
 {  
 public static void main(String[]args)  
      {  
      Tree obj = new Tree();   
      obj.insert(7);  
      obj.insert(5);  
      obj.insert(6);  
      obj.insert(9);  
      obj.insert(4);  
      obj.insert(8);  
      obj.inOrder(obj.getRoot());  
      }  
 }  
 /*======================================================================*/  

Post a Comment

0 Comments