Binary Tree

My Program to create Binary Tree and print sorted output

class Node
  {
      int data ;
      Node left,right;
      Node(int value)
      {
          this.data = value;
          left = null;
          right = null;
      }
  }

  class myTree 
  {
      Node root ;
      myTree () {
          root = null ;
      }
      // apending to tree
      void add(int value) {
          if(root==null)
          {
              root = new Node(value);
              System.out.println("Root created = "+root.data);
              return;
          }
          _add(root,value);
      }

      void _add(Node pointer, int value)
      {
          if(pointer.data < value)
          {
              if(pointer.right != null)
              {
                  _add(pointer.right , value);
              }
              else
              {
                  pointer.right = new Node(value);
                  System.out.println("Inserted "+pointer.right.data+" to right of "+pointer.data);
              }
          }
          else if(pointer.data > value)
          {
              if(pointer.left != null)
              {
                  _add(pointer.left,value);
              }
              else
              {
                  pointer.left = new Node(value);
                  System.out.println("Inserted  "+pointer.left.data+" to left of "+pointer.data);
              }
          }
      }
      void display()
      {
          if(root == null)
          {
              System.out.println("No items in Tree to display :");
              return;
          }
          _display(root);
      }
       public void _display(Node node) {
          if (node != null) {
              _display(node.right);
              System.out.print( node.data + " => ");
              _display(node.left);
          }
       }
  }
  class tree
  {
      public static void main(String[] args) {
          myTree T1 = new myTree();
          for(int i=10;i<90;i+=10)
              T1.add(i);
          T1.display();

      }
  }

Output :

Root created = 10
  Inserted 20 to right of 10
  Inserted 30 to right of 20
  Inserted 40 to right of 30
  Inserted 50 to right of 40
  Inserted 60 to right of 50
  Inserted 70 to right of 60
  Inserted 80 to right of 70
  80 => 70 => 60 => 50 => 40 => 30 => 20 => 10 =>

Popular Posts

Codechef : Program to find if given very large number is divisible by 3 or not

ThreeSum Solution in Java

Creating basic tic tac toe android app using java