Advertisement
ogv

Untitled

ogv
Sep 10th, 2019
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class BSTIterator {
  11. LinkedList<Step> steps;
  12.  
  13. public BSTIterator(TreeNode root) {
  14. steps = new LinkedList<Step>();
  15. steps.add(new Step(root));
  16. }
  17.  
  18. /** @return the next smallest number */
  19. public int next() {
  20. System.out.println("calling next");
  21. move();
  22. int result = steps.getFirst().node.val;
  23. System.out.println("next returned " + result);
  24. return result;
  25. }
  26.  
  27. private void move() {
  28. System.out.println("calling move");
  29. if (steps.isEmpty()) return;
  30.  
  31. for (;;) {
  32. Step step = steps.getFirst();
  33. if (step.visitedLeft == false) {
  34. System.out.println("left from " + step.node.val);
  35. step.visitedLeft = true;
  36. if (step.node.left != null) {
  37. steps.addFirst(new Step(step.node.left));
  38. continue;
  39. }
  40. }
  41.  
  42. if (!step.returned) {
  43. System.out.println("return " + step.node.val);
  44. step.returned = true;
  45. break;
  46. }
  47.  
  48. if (step.visitedRight == false) {
  49. System.out.println("right from " + step.node.val);
  50. step.visitedRight = true;
  51. if (step.node.right != null) {
  52. steps.addFirst(new Step(step.node.right));
  53. continue;
  54. }
  55. }
  56.  
  57. System.out.println("go up");
  58. steps.removeFirst();
  59. }
  60. }
  61.  
  62. /** @return whether we have a next smallest number */
  63. public boolean hasNext() {
  64. System.out.println("calling hasNext");
  65. for (int i = 0; i < steps.size(); i++) {
  66. Step step = steps.get(i);
  67. if (!step.visitedLeft || !step.visitedRight || !step.returned) {
  68. System.out.println("hasNext: true");
  69. return true;
  70. }
  71. }
  72. System.out.println("hasNext: false");
  73. return false;
  74. }
  75.  
  76. class Step {
  77. TreeNode node;
  78. boolean visitedLeft;
  79. boolean visitedRight;
  80. boolean returned;
  81. public Step(TreeNode node ) {
  82. this.node = node;
  83. }
  84. }
  85. }
  86.  
  87. /**
  88. * Your BSTIterator object will be instantiated and called as such:
  89. * BSTIterator obj = new BSTIterator(root);
  90. * int param_1 = obj.next();
  91. * boolean param_2 = obj.hasNext();
  92. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement