Skip to content

Commit 4969f9f

Browse files
iccowanyanglbme
andauthored
Add BFS to binary tree and add note about inorder traversal == DFS (TheAlgorithms#2734)
* Add bfs to binary tree - `Fixes TheAlgorithms#2733` * Add note on the equivalence of dfs and inorder - `Fixes TheAlgorithms#2733` Co-authored-by: Yang Libin <[email protected]>
1 parent 1280321 commit 4969f9f

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

DataStructures/Trees/BinaryTree.java

+37
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package DataStructures.Trees;
22

3+
import java.util.Queue;
4+
import java.util.LinkedList;
5+
36
/**
47
* This entire class is used to build a Binary Tree data structure. There is the Node Class and the
58
* Tree Class, both explained below.
@@ -220,6 +223,7 @@ public Node getRoot() {
220223

221224
/**
222225
* Prints leftChild - root - rightChild
226+
* This is the equivalent of a depth first search
223227
*
224228
* @param localRoot The local root of the binary tree
225229
*/
@@ -256,4 +260,37 @@ public void postOrder(Node localRoot) {
256260
System.out.print(localRoot.data + " ");
257261
}
258262
}
263+
264+
/**
265+
* Prints the tree in a breadth first search order
266+
* This is similar to pre-order traversal, but instead of being
267+
* implemented with a stack (or recursion), it is implemented
268+
* with a queue
269+
*
270+
* @param localRoot The local root of the binary tree
271+
*/
272+
public void bfs(Node localRoot) {
273+
// Create a queue for the order of the nodes
274+
Queue<Node> queue = new LinkedList<Node>();
275+
276+
// If the give root is null, then we don't add to the queue
277+
// and won't do anything
278+
if (localRoot != null)
279+
queue.add(localRoot);
280+
281+
// Continue until the queue is empty
282+
while (! queue.isEmpty()) {
283+
// Get the next node on the queue to visit
284+
localRoot = queue.remove();
285+
286+
// Print the data from the node we are visiting
287+
System.out.print(localRoot.data + " ");
288+
289+
// Add the children to the queue if not null
290+
if (localRoot.right != null)
291+
queue.add(localRoot.right);
292+
if (localRoot.left != null)
293+
queue.add(localRoot.left);
294+
}
295+
}
259296
}

0 commit comments

Comments
 (0)