Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. package BST_A2;
  2.  
  3. import java.util.TreeMap;
  4.  
  5. public class BST implements BST_Interface {
  6. public BST_Node root;
  7. int size;
  8.  
  9. public BST(){ size=0; root=null; }
  10.  
  11. @Override
  12. //used for testing, please leave as is
  13. public BST_Node getRoot(){ return root; }
  14.  
  15. @Override
  16. public boolean insert(String s) {
  17.  
  18. if(root == null){
  19.  
  20. root = new BST_Node(s);
  21.  
  22. size++;
  23. return true;
  24.  
  25. } else {
  26.  
  27. if(root.containsNode(s)){
  28.  
  29. return false;
  30.  
  31. } else{
  32.  
  33. root.insertNode(s);
  34.  
  35. size++;
  36.  
  37. return true;
  38.  
  39. }
  40. }
  41. }
  42.  
  43.  
  44.  
  45. @Override
  46. public boolean remove(String s) {
  47. // check to see if you want to remove the data is the root node
  48. // if it is, make a new node, make the current root left child
  49. if (root == null)
  50. return false;
  51. else{
  52. if (root.data.compareTo(s)==0){
  53. BST_Node fakeRoot = new BST_Node(s);
  54. fakeRoot.left = root;
  55. boolean result = fakeRoot.left.removeNode(s,fakeRoot.left, fakeRoot);
  56. root = fakeRoot.getLeft();
  57. size --;
  58. return result;
  59. }
  60.  
  61. else{
  62. if(root.removeNode(s, root, null)==true){
  63. size -=1;
  64. return true;
  65. }
  66. else{
  67. return false;
  68. }
  69. }
  70. }
  71. }
  72.  
  73.  
  74. @Override
  75. public String findMin() {
  76. if (root == null){
  77. return null;
  78. } else {
  79. return root.findMin().getData();
  80. }
  81. }
  82.  
  83.  
  84. @Override
  85. public String findMax() {
  86. if (root == null){
  87. return null;
  88. }else {
  89. return root.findMax().getData();
  90. }
  91.  
  92. }
  93.  
  94. @Override
  95. public boolean empty() {
  96. return root == null;
  97. }
  98.  
  99. @Override
  100. public boolean contains(String s) {
  101. if(root == null){
  102.  
  103. return false;
  104.  
  105. } else {
  106.  
  107. return root.containsNode(s);
  108. }
  109. }
  110.  
  111.  
  112. @Override
  113. public int size() {
  114. return this.size();
  115. }
  116.  
  117. @Override
  118. public int height() {
  119. return getHeight(root);
  120. }
  121.  
  122. public int getHeight(BST_Node node){
  123. if (node == null) return -1;
  124. return 1 + Math.max(getHeight(node.left), getHeight(node.right));
  125. }
  126. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement