Skip to content

Add BFS to binary tree and add note about inorder traversal == DFS #2734

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 25, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions DataStructures/Trees/BinaryTree.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package DataStructures.Trees;

import java.util.Queue;
import java.util.LinkedList;

/**
* This entire class is used to build a Binary Tree data structure. There is the Node Class and the
* Tree Class, both explained below.
Expand Down Expand Up @@ -220,6 +223,7 @@ public Node getRoot() {

/**
* Prints leftChild - root - rightChild
* This is the equivalent of a depth first search
*
* @param localRoot The local root of the binary tree
*/
Expand Down Expand Up @@ -256,4 +260,37 @@ public void postOrder(Node localRoot) {
System.out.print(localRoot.data + " ");
}
}

/**
* Prints the tree in a breadth first search order
* This is similar to pre-order traversal, but instead of being
* implemented with a stack (or recursion), it is implemented
* with a queue
*
* @param localRoot The local root of the binary tree
*/
public void bfs(Node localRoot) {
// Create a queue for the order of the nodes
Queue<Node> queue = new LinkedList<Node>();

// If the give root is null, then we don't add to the queue
// and won't do anything
if (localRoot != null)
queue.add(localRoot);

// Continue until the queue is empty
while (! queue.isEmpty()) {
// Get the next node on the queue to visit
localRoot = queue.remove();

// Print the data from the node we are visiting
System.out.print(localRoot.data + " ");

// Add the children to the queue if not null
if (localRoot.right != null)
queue.add(localRoot.right);
if (localRoot.left != null)
queue.add(localRoot.left);
}
}
}