Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

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


/*
	This is an implementation that collects the 
	values of the nodes of a binary tree by performing 
	a breadth first search through the tree.
	Let n be the number of binary tree nodes
	Time complexity: O(n) 
	Space complexity: O(n)
*/
import java.util.List;
import java.util.ArrayList;
import java.util.Deque;
import java.util.ArrayDeque;

public class BreadthFirstSearch {
	private BTNode BTRoot;

	public BreadthFirstSearch() {
		/*
		 * Create tree below:
		 * * 1
		 * / 
		 * 2 3
		 * * / 
		 * * 4 5
		 */
		BTRoot = new BTNode(1, null, null);
		BTNode rootLeft = new BTNode(2, null, null);
		BTRoot.left = rootLeft;
		BTNode rootRight = new BTNode(3, null, null);
		BTRoot.right = rootRight;
		BTNode rootRightLeft = new BTNode(4, null, null);
		BTNode rootRightRight = new BTNode(5, null, null);
		rootRight.left = rootRightLeft;
		rootRight.right = rootRightRight;
	}

	public static void main(String[] args) {
		BreadthFirstSearch application = new BreadthFirstSearch();
		List<Integer> values = application.bfsTraversal();
		System.out.println(values); // [1, 2, 3, 4, 5]
	}

	// Perform breadth first traversal through the tree.
	public List<Integer> bfsTraversal() {
		List<Integer> list = new ArrayList<>();
		populateList(BTRoot, list);
		return list;
	}

	// Helper method to populate list by performing
	// breadth first search through the tree.
	private void populateList(BTNode root, List<Integer> list) {
		if (root == null) {
			return;
		}
		Deque<BTNode> queue = new ArrayDeque<>();
		BTNode current;
		queue.add(root);

		while (!queue.isEmpty()) {
			current = queue.removeFirst();
			list.add(current.val);

			if (current.left != null) {
				queue.add(current.left);
			}

			if (current.right != null) {
				queue.add(current.right);
			}
		}
	}

	// Class representing a binary tree node
	// with pointers to value, left, and right nodes
	private class BTNode {
		int val;
		BTNode left;
		BTNode right;

		public BTNode(int val, BTNode left, BTNode right) {
			this.val = val;
			this.left = left;
			this.right = right;
		}
	}
}
Comment

breadth first search BST java

import java.io.*;
import java.util.*;

class Graph
{
    private int V;                              //number of nodes in the graph
    private LinkedList<Integer> adj[];              //adjacency list
    private Queue<Integer> queue;                   //maintaining a queue
 
    Graph(int v)
    {
        V = v;
        adj = new LinkedList[v];
        for (int i=0; i<v; i++)
        {
            adj[i] = new LinkedList<>();
        }
        queue = new LinkedList<Integer>();
    }

 
    void addEdge(int v,int w)
    {
        adj[v].add(w);                          //adding an edge to the adjacency list (edges are bidirectional in this example)
    }
 
    void BFS(int n)
    {

        boolean nodes[] = new boolean[V];       //initialize boolean array for holding the data
        int a = 0;
 
        nodes[n]=true;                  
        queue.add(n);                   //root node is added to the top of the queue
 
        while (queue.size() != 0)
        {
            n = queue.poll();             //remove the top element of the queue
            System.out.print(n+" ");           //print the top element of the queue
 
            for (int i = 0; i < adj[n].size(); i++)  //iterate through the linked list and push all neighbors into queue
            {
                a = adj[n].get(i);
                if (!nodes[a])                    //only insert nodes into queue if they have not been explored already
                {
                    nodes[a] = true;
                    queue.add(a);
                }
            }  
        }
    }

    public static void main(String args[])
    {
        Graph graph = new Graph(6);
 
        graph.addEdge(0, 1);
        graph.addEdge(0, 3);
        graph.addEdge(0, 4);
        graph.addEdge(4, 5);
        graph.addEdge(3, 5);
        graph.addEdge(1, 2);
        graph.addEdge(1, 0);
        graph.addEdge(2, 1);
        graph.addEdge(4, 1);
        graph.addEdge(3, 1);
        graph.addEdge(5, 4);
        graph.addEdge(5, 3);
 
        System.out.println("The Breadth First Traversal of the graph is as follows :");
 
        graph.BFS(0);
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: get current unix timestamp java 
Java :: Calculator Program in Java. 
Java :: java create arraylist 
Java :: selenide wait 
Java :: convert int to string java 
Java :: WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 
Java :: return empty array from method 
Java :: java random uuid 
Java :: execute code after delay java 
Java :: java linkedlist print 
Java :: binding fragment android 
Java :: bigdecimal to string 
Java :: java encrypt string 
Java :: spring h2 database example 
Java :: java get last char of string 
Java :: random java 
Java :: initialize hashset with values java 9 
Java :: java how to check string is number 
Java :: association in java 
Java :: java Modulo 10^9+7 (1000000007) 
Java :: java bukkit double jump 
Java :: Do not concatenate text displayed with setText. Use resource string with placeholders. 
Java :: how to add 2 numbers in java 
Java :: open camera or gallery on button click android 
Java :: function in java 
Java :: charcodeat java 
Java :: how to print to the console in java 
Java :: android imageview set image from drawable programmatically 
Java :: java secretkey 
Java :: copy elements of array in java 
ADD CONTENT
Topic
Content
Source link
Name
9+4 =