fork(1) download
  1. class BinSearchTree {
  2. public static class Node {
  3. private Comparable value;
  4. private Node left;
  5. private Node right;
  6. private Node(Comparable value) {
  7. this.value = value;
  8. this.left = this.right = null;
  9. }
  10. public String toString() {
  11. return "Node(" + value + ")";
  12. }
  13. private static void toString(StringBuilder buf, Node root) {
  14. if (root == null)
  15. return;
  16. toString(buf, root.left);
  17. buf.append(root.value);
  18. buf.append(" ");
  19. toString(buf, root.right);
  20. }
  21. private static Node insert(Comparable value, Node root) {
  22. if (root == null)
  23. return new Node(value);
  24. int cmp = root.value.compareTo(value);
  25. if (cmp < 0)
  26. root.right = insert(value, root.right);
  27. else
  28. root.left = insert(value, root.left);
  29. return root;
  30. }
  31. private static Node remove(Comparable value, Node root) {
  32. if (root == null)
  33. return null;
  34. int cmp = root.value.compareTo(value);
  35. if (cmp == 0) {
  36. if (root.left == null)
  37. return root.right;
  38. if (root.right == null)
  39. return root.left;
  40. Node n = searchLargestNode(root.left);
  41. n.right = root.right;
  42. return n;
  43. } else if (cmp < 0)
  44. root.right = remove(value, root.right);
  45. else
  46. root.left = remove(value, root.left);
  47. return root;
  48. }
  49. private static Node searchLargestNode(Node root) {
  50. if (root.right == null)
  51. return root;
  52. return searchLargestNode(root.right);
  53. }
  54. }
  55.  
  56. private Node rootNode;
  57. public BinSearchTree() {
  58. rootNode = null;
  59. }
  60. public void insert(Comparable value) {
  61. rootNode = Node.insert(value, rootNode);
  62. }
  63. public void remove(Comparable value) {
  64. rootNode = Node.remove(value, rootNode);
  65. }
  66. public String toString() {
  67. StringBuilder buf = new StringBuilder();
  68. buf.append("[");
  69. Node.toString(buf, rootNode);
  70. buf.append("]");
  71. return buf.toString();
  72. }
  73. }
  74.  
  75. class Main {
  76. public static void main(String[] args) {
  77. BinSearchTree tree1 = new BinSearchTree();
  78. for (int i = 0; i < 10; i++) {
  79. tree1.insert((int)(Math.random() * 100));
  80. }
  81. System.out.println(tree1);
  82.  
  83. BinSearchTree tree2 = new BinSearchTree();
  84. tree2.insert(20);
  85. tree2.insert(30);
  86. tree2.insert(10);
  87. tree2.remove(20);
  88. System.out.println(tree2);
  89. }
  90. }
  91.  
  92.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
[9 13 15 26 52 73 84 87 90 96 ]
[10 30 ]