Algorithms: How to use Breadth First Search

    4
/ \
2 5
/ \ \
0 1 8
/ /
7 10
public class Node {
int value;
Node left;
Node right;

public Node(int v) {
value = v;
}
}
// create nodes
Node root = new Node(4);
Node child2 = new Node(2);
Node child5 = new Node(5);
Node child0 = new Node(0);
Node child1 = new Node(1);
Node child8 = new Node(8);
Node child7 = new Node(7);
Node child10 = new Node(10);

// establish relationships
root.left = child2;
root.right = child5;
child2.left = child0;
child2.right = child1;
child5.right = child8;
child1.left = child7;
child8.left = child10;
public static void printDFS(Node root) {
if(root == null) {
return;
}

System.out.println(root.value);
if(root.left != null) {
printDFS(root.left);
}
if(root.right != null) {
printDFS(root.right);
}
}
4
2
0
1
7
5
8
10
public static void printBFS(Node root) {
LinkedList<Node> queue = new LinkedList<Node>();
queue.add(root);

while(queue.size() > 0) {
Node node = queue.remove();
System.out.println(node.value);
if(node.left != null) {
queue.add(node.left);
}
if(node.right != null) {
queue.add(node.right);
}
}
}
4
2
5
0
1
8
7
10
public static void printBFSTreeLevel(Node root) {
LinkedList<Node> queue = new LinkedList<Node>();
queue.add(root);

while(queue.size() > 0) {
int queueSize = queue.size();
for(int i = queueSize; i > 0; i--) {
Node node = queue.remove();
System.out.print(node.value + " ");
if(node.left != null) {
queue.add(node.left);
}
if(node.right != null) {
queue.add(node.right);
}
}
System.out.println();
}
}
4 
2 5
0 1 8
7 10

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store