Can anybody give a link for a simple explanation on BFS and DFS with its implementation?
BFS and DFS are applicable to all kinds of graphs. I explain it for binary tree only. BFS visit each node top to bottom, left to right. For example for this:
1
/ \
7 9
\ / \
8 2 3
BFS gives us: 1 7 9 8 2 3. DFS visits depth of each branch first. Then, it comes back to its parents. You can follow this informal rule. First left child then right child then parent. But, you need to start from the depth of each branch. For example, here you start from 8, since there is no left child for 7. Then, you visit parent 7. Then, 1 parent of 7 will be visited. Then, you go to right branch. But, this time there is 2 as the left most child. So, you visit 2 (left child) then, right child 3 then, 9 their parents. So, DFS gives us 8 7 1 2 9 3. This is the implementation:
import java.util.ArrayList;
import java.util.List;
public class TreeTraverse {
static class Node{
Node(int data){
this.data = data;
this.left = null;
this.right = null;
this.visited = false;
}
int data;
Node left;
Node right;
boolean visited;
}
public static void main(String[] args) {
//The tree:
// 1
// / \
// 7 9
// \ / \
// 8 2 3
Node node1 = new Node(1);
Node node7 = new Node(7);
Node node9 = new Node(9);
Node node8 = new Node(8);
Node node2 = new Node(2);
Node node3 = new Node(3);
node1.left = node7;
node1.right = node9;
node7.right = node8;
node9.right = node3;
node9.left = node2;
System.out.println("DFS: ");
depthFirstSearch(node1);
System.out.println("\nBFS: ");
breadthFirstSearch(node1);
}
private static void depthFirstSearch(Node node){
if(node.left == null && node.right == null){
System.out.print(node.data+" ");
node.visited = true;
}else if(node.left == null || node.left.visited){
depthFirstSearch(node.right);
System.out.print(node.data+" ");
node.visited = true;
}else{
depthFirstSearch(node.left);
node.visited = true;
System.out.print(node.data+" ");
depthFirstSearch(node.right);
}
}
private static void breadthFirstSearch(Node node){
List al = new ArrayList<>();
al.add(node);
while(!al.isEmpty()){
node = al.get(0);
if(node.left != null){
int index = al.size();
al.add(index,node.left);
}
if(node.right != null){
int index = al.size();
al.add(index,node.right);
}
System.out.print(al.get(0).data+" ");
al.remove(0);
}
}
}
I hope it helps. If you want to clone the project, please visit: https://github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/TreeTraverse.java. I hope it helps.