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 <szuyanglb@outlook.com>
This commit is contained in:
Ian Cowan 2021-10-25 02:43:37 -04:00 committed by GitHub
parent 12803218cf
commit 4969f9f153
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,5 +1,8 @@
package DataStructures.Trees; 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 * This entire class is used to build a Binary Tree data structure. There is the Node Class and the
* Tree Class, both explained below. * Tree Class, both explained below.
@ -220,6 +223,7 @@ public class BinaryTree {
/** /**
* Prints leftChild - root - rightChild * Prints leftChild - root - rightChild
* This is the equivalent of a depth first search
* *
* @param localRoot The local root of the binary tree * @param localRoot The local root of the binary tree
*/ */
@ -256,4 +260,37 @@ public class BinaryTree {
System.out.print(localRoot.data + " "); 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);
}
}
} }