fork download
  1. import java.util.Random;
  2.  
  3. class Indirect {
  4. Integer data;
  5. Indirect() { data = null; }
  6. }
  7.  
  8. class Node {
  9. private Integer data;
  10. private Node left;
  11. private Node right;
  12. private Node(Integer data) {
  13. this.data = data;
  14. this.left = this.right = null;
  15. }
  16. public static Node pushNode(Node root, Integer data) {
  17. if (root == null) {
  18. return new Node(data);
  19. } else if (data.intValue() < root.data.intValue()) {
  20. root.left = pushNode(root.left, data);
  21. return root;
  22. } else {
  23. root.right = pushNode(root.right, data);
  24. return root;
  25. }
  26. }
  27. public static Node popNode(Node root, Indirect idata) {
  28. if (root == null) {
  29. idata = null;
  30. return null;
  31. }
  32. if (root.left != null) {
  33. root.left = popNode(root.left, idata);
  34. return root;
  35. }
  36. idata.data = root.data;
  37. return root.right;
  38. }
  39. }
  40.  
  41. class BinTree {
  42. private Node root;
  43. BinTree() { root = null; }
  44. void pushNode(Integer data) { root = Node.pushNode(root, data); }
  45. Integer popNode() {
  46. Indirect idata;
  47. root = Node.popNode(root, idata = new Indirect());
  48. if (root == null && idata == null)
  49. return null;
  50. return idata.data;
  51. }
  52. }
  53.  
  54. class Main {
  55. final static int N = 10;
  56. final static int MAX = 10000;
  57. public static void main(String[] args) {
  58. Random random = new Random();
  59. BinTree root = new BinTree();
  60. Integer data;
  61. for (int i = 0; i < N; i++) {
  62. data = new Integer(random.nextInt(MAX));
  63. root.pushNode(data);
  64. System.out.println(data);
  65. }
  66. System.out.println();
  67.  
  68. while ((data = root.popNode()) != null) {
  69. System.out.println(data);
  70. }
  71. }
  72. }
  73. /* end */
  74.  
Success #stdin #stdout 0.03s 245632KB
stdin
Standard input is empty
stdout
230
9830
3014
2568
9422
8484
4954
5301
720
2743

230
720
2568
2743
3014
4954
5301
8484
9422
9830