55import com .rampatra .common .LinkedQueue ;
66import com .rampatra .common .Queue ;
77
8+ import java .util .LinkedList ;
89import java .util .NoSuchElementException ;
910
1011import static java .lang .System .out ;
@@ -20,13 +21,16 @@ public class BFSUsingQueue {
2021
2122 /**
2223 * Breadth first traversal (Level-order traversal using Queue).
24+ *
25+ * @param node a tree node with left and right references and a value of type {@code E}
26+ * @param <E> the type of value that the {@code node} holds
2327 */
2428 public static <E extends Comparable <E >> void breadthFirstTraversalUsingQueue (BinaryNode <E > node ) {
2529 Queue <BinaryNode <E >> queue = new LinkedQueue <>();
2630 breadthFirstTraversalUsingQueue (node , queue );
2731 }
2832
29- public static <E extends Comparable <E >> void breadthFirstTraversalUsingQueue (BinaryNode <E > node ,
33+ private static <E extends Comparable <E >> void breadthFirstTraversalUsingQueue (BinaryNode <E > node ,
3034 Queue <BinaryNode <E >> queue ) {
3135
3236 if (node != null ) {
@@ -42,12 +46,33 @@ public static <E extends Comparable<E>> void breadthFirstTraversalUsingQueue(Bin
4246 }
4347 }
4448
45- public static <E extends Comparable <E >> void printValue (BinaryNode <E > node ) {
49+ private static <E extends Comparable <E >> void printValue (BinaryNode <E > node ) {
4650 if (node == null ) return ;
4751
4852 out .print (node .value );
4953 }
5054
55+ /**
56+ * Level order traversal using queue but iteratively.
57+ *
58+ * @param root the root node from where the traversal should start
59+ * @param <E> type of the {@code value} that {@code BinaryNode} holds
60+ */
61+ public static <E extends Comparable <E >> void breadthFirstTraversalUsingQueueIterative (BinaryNode <E > root ) {
62+ if (root == null ) return ;
63+
64+ Queue <BinaryNode <E >> q = new LinkedQueue <>();
65+ q .add (root );
66+
67+ while (!q .isEmpty ()) {
68+ BinaryNode <E > node = q .remove ();
69+ out .print (node .value );
70+
71+ if (node .left != null ) q .add (node .left );
72+ if (node .right != null ) q .add (node .right );
73+ }
74+ }
75+
5176 public static void main (String a []) {
5277 BinaryTree <Integer > bt = new BinaryTree <>();
5378 bt .put (6 );
@@ -57,5 +82,7 @@ public static void main(String a[]) {
5782 bt .put (8 );
5883 bt .put (9 );
5984 breadthFirstTraversalUsingQueue (bt .root );
85+ System .out .println ();
86+ breadthFirstTraversalUsingQueueIterative (bt .root );
6087 }
6188}
0 commit comments