Guest User

Untitled

a guest
Mar 21st, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. public class BinarySearchTree {
  2.  
  3. public static class Node {
  4. int key;
  5. Node left;
  6. Node right;
  7.  
  8. public Node (int key) {
  9. this(key, null, null);
  10. }
  11.  
  12. public Node (int key, Node left, Node right) {
  13. this.key = key;
  14. this.left = left;
  15. this.right = right;
  16. }
  17. }
  18.  
  19. public static class BST {
  20. Node parent;
  21. int count;
  22.  
  23. public BST(int parent) {
  24. this.parent = new Node(parent);
  25. }
  26.  
  27. public void insert(int key) {
  28. insert(parent, key);
  29. count += 1;
  30. }
  31.  
  32. public void insert(Node node, int key) {
  33. if (key > node.key) {
  34. if (node.right == null) {
  35. node.right = new Node(key);
  36. } else {
  37. insert(node.right, key);
  38. }
  39. }
  40. if (key < node.key) {
  41. if (node.left == null) {
  42. node.left = new Node(key);
  43. } else {
  44. insert(node.left, key);
  45. }
  46. }
  47. }
  48.  
  49. public boolean exists(int key) {
  50. return exists(key, parent);
  51. }
  52.  
  53. public boolean exists(int key, Node n) {
  54. if (n == null) {
  55. return false;
  56. }
  57. if (n.key == key) {
  58. return true;
  59. }
  60. return exists(key, n.left) || exists(key, n.right);
  61. }
  62.  
  63. public void printTree() {
  64. printTree(parent, 0, 0);
  65. }
  66.  
  67. public void printTree(Node n, int depth, int type) {
  68. if (n == null) {
  69. return;
  70. }
  71. for(int i = 0; i < depth; i++) {
  72. System.out.print("\t");
  73. }
  74. if(type == 0) {
  75. System.out.print("Parent: ");
  76. }
  77. if(type == 1) {
  78. System.out.print("Left: ");
  79. }
  80. if(type == 2) {
  81. System.out.print("Right: ");
  82. }
  83. System.out.print(n.key + "\n");
  84. printTree(n.left, depth + 1, 1);
  85. printTree(n.right, depth + 1, 2);
  86. }
  87.  
  88. }
  89.  
  90. public static void main(String[] args) {
  91. BST tree = new BST(50);
  92. tree.insert(30);
  93. tree.insert(20);
  94. tree.insert(40);
  95. tree.insert(70);
  96. tree.insert(60);
  97. tree.insert(80);
  98. tree.printTree();
  99. System.out.println(tree.exists(40));
  100. System.out.println(tree.exists(69));
  101. }
  102.  
  103. }
Add Comment
Please, Sign In to add comment