ogv

Untitled

ogv
Sep 10th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 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. Step step = steps.getFirst();
  32. if (step.visitedLeft == false) {
  33. System.out.println("left from " + step.node.val);
  34. step.visitedLeft = true;
  35. if (step.node.left != null) {
  36. steps.addFirst(new Step(step.node.left));
  37. move();
  38. }
  39. }
  40.  
  41. if (!step.returned) {
  42. System.out.println("return " + step.node.val);
  43. step.returned = true;
  44. return;
  45. }
  46.  
  47. if (step.visitedRight == false) {
  48. System.out.println("right from " + step.node.val);
  49. step.visitedRight = true;
  50. if (step.node.right != null) {
  51. steps.addFirst(new Step(step.node.right));
  52. move();
  53. }
  54. }
  55.  
  56. System.out.println("go up");
  57. steps.removeFirst();
  58. move();
  59. }
  60.  
  61. /** @return whether we have a next smallest number */
  62. public boolean hasNext() {
  63. System.out.println("calling hasNext");
  64. for (int i = 0; i < steps.size(); i++) {
  65. Step step = steps.get(i);
  66. if (!step.visitedLeft || !step.visitedRight || !step.returned) {
  67. System.out.println("hasNext: true");
  68. return true;
  69. }
  70. }
  71. System.out.println("hasNext: false");
  72. return false;
  73. }
  74.  
  75. class Step {
  76. TreeNode node;
  77. boolean visitedLeft;
  78. boolean visitedRight;
  79. boolean returned;
  80. public Step(TreeNode node ) {
  81. this.node = node;
  82. }
  83. }
  84. }
  85.  
  86. /**
  87. * Your BSTIterator object will be instantiated and called as such:
  88. * BSTIterator obj = new BSTIterator(root);
  89. * int param_1 = obj.next();
  90. * boolean param_2 = obj.hasNext();
  91. */
Advertisement
Add Comment
Please, Sign In to add comment