|
1 | 1 | package DataStructures.Trees;
|
2 | 2 |
|
| 3 | +import java.util.Queue; |
| 4 | +import java.util.LinkedList; |
| 5 | + |
3 | 6 | /**
|
4 | 7 | * This entire class is used to build a Binary Tree data structure. There is the Node Class and the
|
5 | 8 | * Tree Class, both explained below.
|
@@ -220,6 +223,7 @@ public Node getRoot() {
|
220 | 223 |
|
221 | 224 | /**
|
222 | 225 | * Prints leftChild - root - rightChild
|
| 226 | + * This is the equivalent of a depth first search |
223 | 227 | *
|
224 | 228 | * @param localRoot The local root of the binary tree
|
225 | 229 | */
|
@@ -256,4 +260,37 @@ public void postOrder(Node localRoot) {
|
256 | 260 | System.out.print(localRoot.data + " ");
|
257 | 261 | }
|
258 | 262 | }
|
| 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 | + } |
259 | 296 | }
|
0 commit comments