From 4969f9f153e7fb42c1c3956d92f850feddb777c6 Mon Sep 17 00:00:00 2001 From: Ian Cowan <38896380+iccowan@users.noreply.github.com> Date: Mon, 25 Oct 2021 02:43:37 -0400 Subject: [PATCH] Add BFS to binary tree and add note about inorder traversal == DFS (#2734) * Add bfs to binary tree - `Fixes #2733` * Add note on the equivalence of dfs and inorder - `Fixes #2733` Co-authored-by: Yang Libin --- DataStructures/Trees/BinaryTree.java | 37 ++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/DataStructures/Trees/BinaryTree.java b/DataStructures/Trees/BinaryTree.java index 9afbf6f0..a9003d4b 100644 --- a/DataStructures/Trees/BinaryTree.java +++ b/DataStructures/Trees/BinaryTree.java @@ -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. @@ -220,6 +223,7 @@ public class BinaryTree { /** * Prints leftChild - root - rightChild + * This is the equivalent of a depth first search * * @param localRoot The local root of the binary tree */ @@ -256,4 +260,37 @@ public class BinaryTree { 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 queue = new LinkedList(); + + // 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); + } + } }