Breadth First Search tree in Java
Breadth-first search (BFS) is an algorithm for traversing or searching a graph, tree, or other data structure. It starts at the root node and explores the neighbor nodes first, before moving to the next level neighbors.
Here is an example of how you might implement breadth-first search in Java:
import java.util.ArrayDeque;
import java.util.Deque;
class Node {
int data;
Node left;
Node right;
public Node(int data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
}
class BinaryTree {
private Node root;
public BinaryTree(Node root) {
this.root = root;
}
public void breadthFirstSearch() {
Deque<Node> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()) {
Node node = queue.pollFirst();
System.out.println(node.data);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
}
0 Comments
if you are not getting it then ask i am glad to help