5
5
import com .rampatra .common .LinkedQueue ;
6
6
import com .rampatra .common .Queue ;
7
7
8
+ import java .util .LinkedList ;
8
9
import java .util .NoSuchElementException ;
9
10
10
11
import static java .lang .System .out ;
@@ -20,13 +21,16 @@ public class BFSUsingQueue {
20
21
21
22
/**
22
23
* 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
23
27
*/
24
28
public static <E extends Comparable <E >> void breadthFirstTraversalUsingQueue (BinaryNode <E > node ) {
25
29
Queue <BinaryNode <E >> queue = new LinkedQueue <>();
26
30
breadthFirstTraversalUsingQueue (node , queue );
27
31
}
28
32
29
- public static <E extends Comparable <E >> void breadthFirstTraversalUsingQueue (BinaryNode <E > node ,
33
+ private static <E extends Comparable <E >> void breadthFirstTraversalUsingQueue (BinaryNode <E > node ,
30
34
Queue <BinaryNode <E >> queue ) {
31
35
32
36
if (node != null ) {
@@ -42,12 +46,33 @@ public static <E extends Comparable<E>> void breadthFirstTraversalUsingQueue(Bin
42
46
}
43
47
}
44
48
45
- public static <E extends Comparable <E >> void printValue (BinaryNode <E > node ) {
49
+ private static <E extends Comparable <E >> void printValue (BinaryNode <E > node ) {
46
50
if (node == null ) return ;
47
51
48
52
out .print (node .value );
49
53
}
50
54
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
+
51
76
public static void main (String a []) {
52
77
BinaryTree <Integer > bt = new BinaryTree <>();
53
78
bt .put (6 );
@@ -57,5 +82,7 @@ public static void main(String a[]) {
57
82
bt .put (8 );
58
83
bt .put (9 );
59
84
breadthFirstTraversalUsingQueue (bt .root );
85
+ System .out .println ();
86
+ breadthFirstTraversalUsingQueueIterative (bt .root );
60
87
}
61
88
}
0 commit comments