fork download
  1. import java.util.Random;
  2.  
  3. class Indirect {
  4. int data;
  5. boolean flag;
  6. }
  7.  
  8. class Node {
  9. private int data;
  10. private Node left;
  11. private Node right;
  12. private Node(int data) {
  13. this.data = data;
  14. this.left = this.right = null;
  15. }
  16. public static Node pushNode(Node root, int data) {
  17. if (root == null) {
  18. return new Node(data);
  19. } else if (data < root.data) {
  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.flag = false;
  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. idata.flag = true;
  38. return root.right;
  39. }
  40. }
  41.  
  42. class BinTree {
  43. private Node root;
  44. BinTree() { root = null; }
  45. void pushNode(int data) { root = Node.pushNode(root, data); }
  46. Indirect popNode() {
  47. Indirect idata;
  48. root = Node.popNode(root, idata = new Indirect());
  49. if (idata.flag == false)
  50. return null;
  51. return idata;
  52. }
  53. }
  54.  
  55. class Main {
  56. final static int N = 10;
  57. final static int MAX = 1000;
  58. public static void main(String[] args) {
  59. Random random = new Random();
  60. BinTree root = new BinTree();
  61. int data;
  62. for (int i = 0; i < N; i++) {
  63. data = random.nextInt(MAX);
  64. root.pushNode(data);
  65. }
  66. Indirect idata;
  67. while ((idata = root.popNode()) != null) {
  68. int rdata = idata.data;
  69. System.out.println(rdata);
  70. }
  71. }
  72. }
  73. /* end */
  74.  
Success #stdin #stdout 0.03s 245632KB
stdin
Standard input is empty
stdout
277
309
371
435
451
517
531
608
842
863