fork download
  1. import java.util.Random;
  2.  
  3.  
  4. public class Main {
  5. public static void main(String[] args) {
  6. Random random = new Random();
  7. BinaryTree tree = new BinaryTree();
  8. for (int i = 0; i < 10; i++) {
  9. tree.add(random.nextInt(10));
  10. }
  11. tree.dump();
  12. }
  13. }
  14.  
  15. class BinaryTree {
  16. Node root = new EmptyNode();
  17.  
  18. void add(int value) {
  19. this.root.add(new RootResult(this), value);
  20. }
  21.  
  22. void dump() {
  23. this.root.dump("");
  24. }
  25. }
  26.  
  27. interface Node {
  28. void add(Result result, int value);
  29. void dump(String space);
  30. }
  31.  
  32. class EmptyNode implements Node {
  33. @Override
  34. public void add(Result result, int value) {
  35. result.setResult(new ValueNode(value, this, this));
  36. }
  37.  
  38. @Override
  39. public void dump(String space) {
  40. }
  41. }
  42.  
  43. class ValueNode implements Node {
  44. int value;
  45. Node left;
  46. Node right;
  47.  
  48. ValueNode(int value, Node left, Node right) {
  49. this.value = value;
  50. this.left = left;
  51. this.right = right;
  52. }
  53.  
  54. @Override
  55. public void add(Result result, int value) {
  56. if (value < this.value) {
  57. this.left.add(new LeftResult(this), value);
  58. } else {
  59. this.right.add(new RightResult(this), value);
  60. }
  61. }
  62.  
  63. @Override
  64. public void dump(String space) {
  65. this.right.dump(space + " ");
  66. System.out.println(space + this.value);
  67. this.left.dump(space + " ");
  68. }
  69. }
  70.  
  71. interface Result {
  72. void setResult(ValueNode valueNode);
  73. }
  74.  
  75. class RootResult implements Result {
  76. BinaryTree tree;
  77.  
  78. RootResult(BinaryTree tree) {
  79. this.tree = tree;
  80. }
  81.  
  82. @Override
  83. public void setResult(ValueNode root) {
  84. tree.root = root;
  85. }
  86. }
  87.  
  88. class LeftResult implements Result {
  89. ValueNode node;
  90.  
  91. LeftResult(ValueNode node) {
  92. this.node = node;
  93. }
  94.  
  95. @Override
  96. public void setResult(ValueNode left) {
  97. node.left = left;
  98. }
  99. }
  100.  
  101. class RightResult implements Result {
  102. ValueNode node;
  103.  
  104. RightResult(ValueNode node) {
  105. this.node = node;
  106. }
  107.  
  108. @Override
  109. public void setResult(ValueNode right) {
  110. node.right = right;
  111. }
  112. }
  113.  
  114.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
  9
9
        7
      7
    6
        5
      4
  4
      0
    0