Skip to content

Commit 7dacb2f

Browse files
authored
Merge pull request TheAlgorithms#164 from KyleScharnhorst/master
Add: level order traversal.
2 parents 5f24928 + a9e8b6b commit 7dacb2f

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

data_structures/Trees/TreeTraversal.java

+27-3
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,33 @@
33
* @author Varun Upadhyay (https://github.com/varunu28)
44
*
55
*/
6+
import java.util.LinkedList;
67

78
// Driver Program
89
public class TreeTraversal {
910
public static void main(String[] args) {
1011
Node tree = new Node(5);
1112
tree.insert(3);
1213
tree.insert(7);
14+
tree.insert(1);
15+
tree.insert(9);
1316

14-
// Prints 3 5 7
17+
// Prints 1 3 5 7 9
1518
tree.printInOrder();
1619
System.out.println();
1720

18-
// Prints 5 3 7
21+
// Prints 5 3 1 7 9
1922
tree.printPreOrder();
2023
System.out.println();
2124

22-
// Prints 3 7 5
25+
// Prints 1 3 9 7 5
2326
tree.printPostOrder();
2427
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();
2533
}
2634
}
2735

@@ -31,6 +39,7 @@ public static void main(String[] args) {
3139
* printInOrder: LEFT -> ROOT -> RIGHT
3240
* printPreOrder: ROOT -> LEFT -> RIGHT
3341
* printPostOrder: LEFT -> RIGHT -> ROOT
42+
* printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc
3443
*/
3544
class Node {
3645
Node left, right;
@@ -88,5 +97,20 @@ public void printPostOrder() {
8897
}
8998
System.out.print(data + " ");
9099
}
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+
}
91115
}
92116

0 commit comments

Comments
 (0)