-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree:LevelOrderTraversal.java
More file actions
38 lines (29 loc) · 934 Bytes
/
Copy pathTree:LevelOrderTraversal.java
File metadata and controls
38 lines (29 loc) · 934 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
class Node
int data;
Node left;
Node right;
*/
void levelOrder(Node root) {
java.util.LinkedList<Node> queue = new java.util.LinkedList<Node>();
java.util.LinkedList<Integer> output = new java.util.LinkedList<Integer>();
queue.push(root);
while (!queue.isEmpty()) {
Node cur = queue.poll();
output.add(cur.data);
if (cur.left != null) {
queue.add(cur.left);
}
if (cur.right != null) {
queue.add(cur.right);
}
}
StringBuilder sb = new StringBuilder();
if (output.size() > 0) {
sb.append(output.get(0));
}
for (int i = 1; i < output.size(); i++) {
sb.append(" " + output.get(i));
}
System.out.println(sb.toString());
}