How to perform breadth first search through a binary tree, in Java?

How to perform breadth first search through a binary tree, in Java?

To perform a breadth-first search (BFS) through a binary tree in Java, you can use a queue data structure to store the nodes as they are visited and traverse the tree level by level.

Here is an example of how you can perform a BFS through a binary tree in Java:

refer to‮tual:‬turi.com
import java.util.LinkedList;
import java.util.Queue;

public class BinaryTree {
    private Node root;
    
    private static class Node {
        int data;
        Node left;
        Node right;
        
        Node(int data) {
            this.data = data;
        }
    }
    
    public void breadthFirstSearch() {
        if (root == null) {
            return;
        }
        
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        
        while (!queue.isEmpty()) {
            Node current = queue.remove();
            System.out.print(current.data + " ");
            if (current.left != null) {
                queue.add(current.left);
            }
            if (current.right != null) {
                queue.add(current.right);
            }
        }
    }
}

In this example, the BinaryTree class has a breadthFirstSearch method that performs a BFS through the tree. The method starts by adding the root node to the queue, and then it enters a loop that continues until the queue is empty.

In each iteration of the loop, the front node of the queue is removed using the remove method and its data is printed. Then, the left and right children of the node are added to the queue, if they exist. This process continues until all the nodes of the tree have been visited.

The BFS algorithm traverses the tree level by level, starting from the root node and going down to the leaf nodes. The time complexity of the BFS algorithm is O(n), where n is the number of nodes in the tree.

Keep in mind that this is just one way to perform a BFS through a binary tree in Java. You can use different data structures and techniques to achieve the same result, such as using a stack data structure to perform a depth-first search (DFS) through the tree.

Created Time:2017-11-01 20:42:48  Author:lautturi