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

297
1389
1643
2254
5327
5623
5702
5961
7144
7288