|
1 | 1 | package com.jwetherell.algorithms.data_structures; |
2 | 2 |
|
| 3 | +import java.util.ArrayDeque; |
3 | 4 | import java.util.ArrayList; |
4 | 5 | import java.util.List; |
5 | 6 | import java.util.Random; |
6 | | - |
| 7 | +import java.util.Queue; |
7 | 8 |
|
8 | 9 | /** |
9 | 10 | * A binary search tree (BST), which may sometimes also be called an ordered or |
@@ -450,13 +451,33 @@ protected boolean validateNode(Node<T> node) { |
450 | 451 | } |
451 | 452 |
|
452 | 453 | /** |
453 | | - * Get an array representation of the tree in sorted order. |
| 454 | + * Get an array representation of the tree in breath first search order. |
454 | 455 | * |
455 | | - * @return sorted array representing the tree. |
| 456 | + * @return breath first search sorted array representing the tree. |
456 | 457 | */ |
457 | 458 | @SuppressWarnings("unchecked") |
458 | | - public T[] getSorted() { |
459 | | - // Depth first search to traverse the tree in order. |
| 459 | + public T[] getBFS() { |
| 460 | + Queue<Node<T>> queue = new ArrayDeque<Node<T>>(); |
| 461 | + T[] values = (T[]) new Comparable[size]; |
| 462 | + int count = 0; |
| 463 | + Node<T> node = root; |
| 464 | + while (node!=null) { |
| 465 | + values[count++] = node.id; |
| 466 | + if (node.lesser!=null) queue.add(node.lesser); |
| 467 | + if (node.greater!=null) queue.add(node.greater); |
| 468 | + if (!queue.isEmpty()) node = queue.remove(); |
| 469 | + else node = null; |
| 470 | + } |
| 471 | + return values; |
| 472 | + } |
| 473 | + |
| 474 | + /** |
| 475 | + * Get an array representation of the tree in depth first search order. |
| 476 | + * |
| 477 | + * @return depth first search sorted array representing the tree. |
| 478 | + */ |
| 479 | + @SuppressWarnings("unchecked") |
| 480 | + public T[] getDFS() { |
460 | 481 | List<Node<T>> added = new ArrayList<Node<T>>(2); |
461 | 482 | T[] nodes = (T[]) new Comparable[size]; |
462 | 483 | int index = 0; |
@@ -490,6 +511,16 @@ public T[] getSorted() { |
490 | 511 | } |
491 | 512 | return nodes; |
492 | 513 | } |
| 514 | + |
| 515 | + /** |
| 516 | + * Get an array representation of the tree in sorted order. |
| 517 | + * |
| 518 | + * @return sorted array representing the tree. |
| 519 | + */ |
| 520 | + public T[] getSorted() { |
| 521 | + // Depth first search to traverse the tree in order. |
| 522 | + return getDFS(); |
| 523 | + } |
493 | 524 |
|
494 | 525 | /** |
495 | 526 | * {@inheritDoc} |
|
0 commit comments