-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLevelOrderTraversal.java
85 lines (55 loc) · 1.48 KB
/
LevelOrderTraversal.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.LinkedList;
import java.util.Queue;
public class LevelOrderTraversal {
class Node {
int data;
Node left;
Node right;
}
public void levelOrderTraversal(Node root) {
if (root == null) {
System.out.println("Tree is empty.");
return;
}
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (true) {
int queueSize = queue.size();
if (queueSize == 0) {
break;
}
while (queueSize > 0) {
Node current = queue.poll();
System.out.print(current.data + " ");
if (current.left != null) {
queue.add(current.left);
}
if (current.right != null) {
queue.add(current.right);
}
queueSize--;
}
System.out.println();
}
}
public Node createNewNode(int data) {
Node node = new Node();
node.data = data;
node.left = null;
node.right = null;
return node;
}
public static void main(String[] args) {
LevelOrderTraversal lot = new LevelOrderTraversal();
Node root = lot.createNewNode(2);
root.left = lot.createNewNode(7);
root.right = lot.createNewNode(5);
root.left.left = lot.createNewNode(2);
root.left.right = lot.createNewNode(6);
root.left.right.left = lot.createNewNode(5);
root.left.right.right = lot.createNewNode(11);
root.right.right = lot.createNewNode(9);
root.right.right.left = lot.createNewNode(4);
lot.levelOrderTraversal(root);
}
}