forked from msaimraz/Hacktoberfest_2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS.java
37 lines (30 loc) · 891 Bytes
/
BFS.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
import java.util.ArrayDeque;
import java.util.Queue;
public class BFS {
public static void main(String[] args) {
TreeNode root = new TreeNode();
root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
BFS(root);
}
public static void BFS(TreeNode root) {
if (root == null) {
System.out.println("NULL");
}
Queue<TreeNode> list = new ArrayDeque<>();
list.add(root);
while (!list.isEmpty()) {
TreeNode node = list.poll();
System.out.println(node.val);
if (node.left != null) {
list.add(node.left);
}
if (node.right != null) {
list.add(node.right);
}
}
}
}