File tree 1 file changed +27
-3
lines changed
1 file changed +27
-3
lines changed Original file line number Diff line number Diff line change 3
3
* @author Varun Upadhyay (https://github.com/varunu28)
4
4
*
5
5
*/
6
+ import java .util .LinkedList ;
6
7
7
8
// Driver Program
8
9
public class TreeTraversal {
9
10
public static void main (String [] args ) {
10
11
Node tree = new Node (5 );
11
12
tree .insert (3 );
12
13
tree .insert (7 );
14
+ tree .insert (1 );
15
+ tree .insert (9 );
13
16
14
- // Prints 3 5 7
17
+ // Prints 1 3 5 7 9
15
18
tree .printInOrder ();
16
19
System .out .println ();
17
20
18
- // Prints 5 3 7
21
+ // Prints 5 3 1 7 9
19
22
tree .printPreOrder ();
20
23
System .out .println ();
21
24
22
- // Prints 3 7 5
25
+ // Prints 1 3 9 7 5
23
26
tree .printPostOrder ();
24
27
System .out .println ();
28
+
29
+ // Add a couple more nodes for print level test
30
+ // Print 5 3 7 1 9
31
+ tree .printLevelOrder ();
32
+ System .out .println ();
25
33
}
26
34
}
27
35
@@ -31,6 +39,7 @@ public static void main(String[] args) {
31
39
* printInOrder: LEFT -> ROOT -> RIGHT
32
40
* printPreOrder: ROOT -> LEFT -> RIGHT
33
41
* printPostOrder: LEFT -> RIGHT -> ROOT
42
+ * printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc
34
43
*/
35
44
class Node {
36
45
Node left , right ;
@@ -88,5 +97,20 @@ public void printPostOrder() {
88
97
}
89
98
System .out .print (data + " " );
90
99
}
100
+
101
+ public void printLevelOrder () {
102
+ LinkedList <Node > queue = new LinkedList <>();
103
+ queue .add (this );
104
+ while (!queue .isEmpty ()) {
105
+ Node n = queue .poll ();
106
+ System .out .print (n .data + " " );
107
+ if (n .left != null ) {
108
+ queue .add (n .left );
109
+ }
110
+ if (n .right != null ) {
111
+ queue .add (n .right );
112
+ }
113
+ }
114
+ }
91
115
}
92
116
You can’t perform that action at this time.
0 commit comments