You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.5 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. // Binary Search Tree class
  2. // Xiwei Wang
  3. import java.util.*;
  4. public class BST {
  5. // instance variables
  6. private BSTNode m_root;
  7. private int m_size;
  8. // constructor
  9. public BST() {
  10. m_root = null;
  11. m_size = 0;
  12. }
  13. // This method returns the number of elements in the tree.
  14. // Do not make any changes to this method!
  15. public int size() {
  16. return m_size;
  17. }
  18. // This method clears the content of the tree.
  19. // Do not make any changes to this method!
  20. public void clear() {
  21. m_root = null;
  22. m_size = 0;
  23. }
  24. // This non-recursive method takes a string and inserts it into the binary
  25. // search tree, keeping the tree ordered.
  26. public void add(String value) {
  27. BSTNode to_add = new BSTNode(value);
  28. if (m_root == null)
  29. m_root = to_add;
  30. else {
  31. BSTNode current = m_root;
  32. BSTNode parent = null;
  33. int comparison = 0;
  34. while (current != null) {
  35. comparison = value.compareTo(current.getInfo());
  36. if (comparison > 0) {
  37. parent = current;
  38. current = current.getRight();
  39. }
  40. else if (comparison < 0) {
  41. parent = current;
  42. current = current.getRight();
  43. }
  44. else
  45. return;
  46. }
  47. if (comparison > 0)
  48. parent.setRight(to_add);
  49. else
  50. parent.setLeft(to_add);
  51. }
  52. }
  53. // This non-recursive method returns a string that represents the in-order traversal
  54. // of the binary search tree.
  55. public String inOrder() {
  56. // TODO: implement this method using a non-recursive solution
  57. return ""; // replace this statement with your own return
  58. }
  59. // This method returns the smallest element in the binary search tree. You
  60. // are not allowed to create any additional structures, including but not
  61. // limited to arrays, stacks, queues, or other trees.
  62. public String min() {
  63. BSTNode current = m_root;
  64. while (current.getLeft() != null)
  65. current = current.getLeft();
  66. return current.getInfo();
  67. }
  68. // This method takes a reference to the root of the expression, evaluates
  69. // the tree, and returns the result as an int.
  70. public int evaluate(BSTNode node) {
  71. // TODO: implement this method using a non-recursive solution
  72. return -1; // replace this statement with your own return
  73. }
  74. }