Print Binary Search Tree Level By Level – Java Source Code

Print all nodes level by level


   public static void printlevelByLevel(Node root)
   {
      Node current = root;
      Queue q = new Queue();
      q.add(root);
      while(!q.isEmpty())
      {
        Node c =(Node) q.remove();
        System.out.print(c.val+",");
        if(c.left!=null)q.add(c.left);
        if(c.right!=null)q.add(c.right);
      }
   }

Print all nodes level by level and priting also when each level finishes


      public static void printlevelByLevel2Queues(Node root)
   {
      Node current = root;
      Queue q[] = new Queue[]{new Queue(),new Queue()};
      int currentQ=0;
      q[currentQ].add(root);
      while(!q[currentQ].isEmpty() || !q[1-currentQ].isEmpty() )
      {
        if(q[currentQ].isEmpty())
        {
          System.out.println("One level Finished... Switching queue...");
          currentQ = 1- currentQ;
        }
        Node c =(Node) q[currentQ].remove();
        System.out.print(c.val+",");
        if(c.left!=null)q[1-currentQ].add(c.left);
        if(c.right!=null)q[1-currentQ].add(c.right);
      }
   }

2 Comments

  1. Webmaster says:

    Please e-mail me your contacts. I have a question webmaster@spottovo.ru” rel=”nofollow”>……

    Thank you!!!…

  2. ROLAND says:

    Pillspot.org. Canadian Health&Care.No prescription online pharmacy.Special Internet Prices.PillSpot.org. Vitamins@buy.online” rel=”nofollow”>.…

    Categories: Weight Loss.Skin Care.Mens Health.Antiviral.Anxiety/Sleep Aid.Eye Care.Anti-allergic/Asthma.Mental HealthWomens Health.Vitamins/Herbal Supplements.Blood Pressure/Heart.Antibiotics.Antidiabetic.Stop SmokingPain Relief.Stomach.Antidepres…

Leave a Reply