3
3
import java .util .ArrayDeque ;
4
4
import java .util .Queue ;
5
5
6
- import trees .InorderTraversal .Node ;
7
-
8
6
public class BTreeLevelOrderTraversal {
9
7
10
8
static class Node {
@@ -32,6 +30,8 @@ public static void main(String[] args) {
32
30
tree .root .left .left = new Node (25 );
33
31
tree .root .left .right = new Node (75 );
34
32
tree .root .right .right = new Node (350 );
33
+ tree .root .right .right .right = new Node (380 );
34
+ tree .root .right .right .left = new Node (320 );
35
35
36
36
level_traverse (tree .root );
37
37
@@ -40,15 +40,34 @@ public static void main(String[] args) {
40
40
private static void level_traverse (Node root2 ) {
41
41
42
42
if (root2 ==null ) System .out .println ("Tree is empty" );
43
+
43
44
Queue <Node > curr = new ArrayDeque <>();
45
+ Node null_node = new Node (0 );
46
+
47
+ curr .add (root2 );
48
+ curr .add (null_node );
44
49
45
50
while (!curr .isEmpty ()){
46
- curr .add (root2 );
51
+
52
+ if (curr .peek ().left !=null ){
53
+ curr .add (curr .peek ().left );
54
+ }
55
+
56
+ if (!(curr .peek ().right ==null )){
57
+ curr .add (curr .peek ().right );
58
+ }
59
+
60
+ System .out .print (curr .poll ().data +"," );
61
+
62
+ if (curr .peek ()==null_node ){
63
+ System .out .println ("" );
64
+ curr .poll ();
65
+ if (!curr .isEmpty ()){
66
+ curr .add (null_node );
67
+ }
68
+ }
47
69
48
70
}
49
-
50
-
51
-
52
71
}
53
72
54
73
}
0 commit comments