File tree Expand file tree Collapse file tree 1 file changed +30
-6
lines changed Expand file tree Collapse file tree 1 file changed +30
-6
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .LinkedList ;
2
+
1
3
/**
2
4
*
3
5
* @author Varun Upadhyay (https://github.com/varunu28)
@@ -9,19 +11,27 @@ public class TreeTraversal {
9
11
public static void main (String [] args ) {
10
12
Node tree = new Node (5 );
11
13
tree .insert (3 );
14
+ tree .insert (2 );
12
15
tree .insert (7 );
16
+ tree .insert (4 );
17
+ tree .insert (6 );
18
+ tree .insert (8 );
13
19
14
- // Prints 3 5 7
15
- tree .printInOrder ();
20
+ System . out . println ( "Pre order traversal:" );
21
+ tree .printPreOrder ();
16
22
System .out .println ();
17
23
18
- // Prints 5 3 7
19
- tree .printPreOrder ();
24
+ System . out . println ( "In order traversal:" );
25
+ tree .printInOrder ();
20
26
System .out .println ();
21
27
22
- // Prints 3 7 5
28
+ System . out . println ( "Post order traversal:" );
23
29
tree .printPostOrder ();
24
30
System .out .println ();
31
+
32
+ System .out .println ("Level order traversal:" );
33
+ tree .printLevelOrder ();
34
+ System .out .println ();
25
35
}
26
36
}
27
37
@@ -88,5 +98,19 @@ public void printPostOrder() {
88
98
}
89
99
System .out .print (data + " " );
90
100
}
91
- }
92
101
102
+ public void printLevelOrder () {
103
+ LinkedList <Node > queue = new LinkedList <>();
104
+ queue .add (this );
105
+ while (queue .size () > 0 ) {
106
+ Node head = queue .remove ();
107
+ System .out .print (head .data + " " );
108
+ if (head .left != null ) {
109
+ queue .add (head .left );
110
+ }
111
+ if (head .right != null ) {
112
+ queue .add (head .right );
113
+ }
114
+ }
115
+ }
116
+ }
You can’t perform that action at this time.
0 commit comments