Skip to content

Instantly share code, notes, and snippets.

Last active July 30, 2018 18:23
What would you like to do?
Check for path in a tree in a BFS method
// custom node class
public static class Node {
int id;
Node left;
Node right;
public Node(int id){ = id;
public static boolean hasPathBFS(Node source, int destination){
// create a queue for nodes to be checked
Queue<Node> nextToCheck = new LinkedList<Node>();
// create set to temporarily store the id of the nodes we check
HashSet<Integer> visited = new HashSet<>();
// add source node into the queue for checking
// check nodes in queue
// get head node and remove from queue
Node node = nextToCheck.poll();
// head node null check
if(node == null) return false;
// check node
if( == destination) return true;
// mark node as visited
if(!visited.contains( visited.add(;
// add children in the next to check queue
// if no path found
return false;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment