lots of exercises in java... from https://github.com/exercism/java

BinarySearchTree.java 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import java.util.*;
  2. class BinarySearchTree<T extends Comparable<T>> {
  3. private Node<T> root;
  4. private int nodeCount = 0;
  5. void insert(T value) {
  6. if (root == null) {
  7. root = new Node<>(value);
  8. } else {
  9. insert(root, value);
  10. }
  11. nodeCount++;
  12. }
  13. List<T> getAsSortedList() {
  14. List<T> result = new ArrayList<>(nodeCount);
  15. putInSortedOrderToList(root, result);
  16. return Collections.unmodifiableList(result);
  17. }
  18. List<T> getAsLevelOrderList() {
  19. List<T> result = new ArrayList<>(nodeCount);
  20. putInLevelOrderToList(root, result);
  21. return Collections.unmodifiableList(result);
  22. }
  23. Node<T> getRoot() {
  24. return root;
  25. }
  26. private void insert(Node<T> node, T value) {
  27. if (value.compareTo(node.getData()) <= 0) {
  28. if (node.getLeft() == null) {
  29. node.setLeft(new Node<>(value));
  30. } else {
  31. insert(node.getLeft(), value);
  32. }
  33. } else {
  34. if (node.getRight() == null) {
  35. node.setRight(new Node<>(value));
  36. } else {
  37. insert(node.getRight(), value);
  38. }
  39. }
  40. }
  41. private void putInSortedOrderToList(Node<T> node, List<T> list) {
  42. if (node == null || list == null) {
  43. return;
  44. }
  45. if (node.getLeft() != null) {
  46. putInSortedOrderToList(node.getLeft(), list);
  47. }
  48. list.add(node.getData());
  49. if (node.getRight() != null) {
  50. putInSortedOrderToList(node.getRight(), list);
  51. }
  52. }
  53. private void putInLevelOrderToList(Node<T> node, List<T> list) {
  54. if (node == null || list == null) {
  55. return;
  56. }
  57. final Queue<Node<T>> queue = new LinkedList<>();
  58. Node<T> myNode;
  59. Node<T> left;
  60. Node<T> right;
  61. queue.add(node);
  62. while (!queue.isEmpty()) {
  63. myNode = queue.poll();
  64. list.add(myNode.getData());
  65. left = myNode.getLeft();
  66. right = myNode.getRight();
  67. if (left != null) {
  68. queue.add(left);
  69. }
  70. if (right != null) {
  71. queue.add(right);
  72. }
  73. }
  74. }
  75. static class Node<T> {
  76. private T data;
  77. private Node<T> left = null;
  78. private Node<T> right = null;
  79. Node(T data) {
  80. this.data = data;
  81. }
  82. Node<T> getLeft() {
  83. return left;
  84. }
  85. void setLeft(Node<T> left) {
  86. this.left = left;
  87. }
  88. Node<T> getRight() {
  89. return right;
  90. }
  91. void setRight(Node<T> right) {
  92. this.right = right;
  93. }
  94. T getData() {
  95. return data;
  96. }
  97. }
  98. }