1
1
import java .util .LinkedList ;
2
2
3
3
/**
4
- *
5
- * @author Varun Upadhyay (https://github.com/varunu28)
6
- *
7
- */
4
+ *
5
+ * @author Varun Upadhyay (https://github.com/varunu28)
6
+ *
7
+ */
8
8
9
9
// Driver Program
10
10
public class TreeTraversal {
@@ -17,31 +17,33 @@ public static void main(String[] args) {
17
17
tree .insert (6 );
18
18
tree .insert (8 );
19
19
20
+ // Prints 5 3 2 4 7 6 8
20
21
System .out .println ("Pre order traversal:" );
21
22
tree .printPreOrder ();
22
23
System .out .println ();
23
-
24
+ // Prints 2 3 4 5 6 7 8
24
25
System .out .println ("In order traversal:" );
25
26
tree .printInOrder ();
26
27
System .out .println ();
27
-
28
+ // Prints 2 4 3 6 8 7 5
28
29
System .out .println ("Post order traversal:" );
29
30
tree .printPostOrder ();
30
31
System .out .println ();
31
-
32
+ // Prints 5 3 7 2 4 6 8
32
33
System .out .println ("Level order traversal:" );
33
34
tree .printLevelOrder ();
34
35
System .out .println ();
35
36
}
36
37
}
37
38
38
39
/**
39
- * The Node class which initializes a Node of a tree
40
- * Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder
41
- * printInOrder: LEFT -> ROOT -> RIGHT
42
- * printPreOrder: ROOT -> LEFT -> RIGHT
43
- * printPostOrder: LEFT -> RIGHT -> ROOT
44
- */
40
+ * The Node class which initializes a Node of a tree
41
+ * Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder
42
+ * printInOrder: LEFT -> ROOT -> RIGHT
43
+ * printPreOrder: ROOT -> LEFT -> RIGHT
44
+ * printPostOrder: LEFT -> RIGHT -> ROOT
45
+ * printLevelOrder: Prints by level (starting at root), from left to right.
46
+ */
45
47
class Node {
46
48
Node left , right ;
47
49
int data ;
@@ -99,18 +101,23 @@ public void printPostOrder() {
99
101
System .out .print (data + " " );
100
102
}
101
103
104
+ /**
105
+ * O(n) time algorithm.
106
+ * Uses O(n) space to store nodes in a queue to aid in traversal.
107
+ */
102
108
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
- }
109
+ LinkedList <Node > queue = new LinkedList <>();
110
+ queue .add (this );
111
+ while (queue .size () > 0 ) {
112
+ Node head = queue .remove ();
113
+ System .out .print (head .data + " " );
114
+ // Add children of recently-printed node to queue, if they exist.
115
+ if (head .left != null ) {
116
+ queue .add (head .left );
117
+ }
118
+ if (head .right != null ) {
119
+ queue .add (head .right );
120
+ }
121
+ }
122
+ }
116
123
}
0 commit comments