|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * public class TreeNode { |
| 4 | + * int val; |
| 5 | + * TreeNode left; |
| 6 | + * TreeNode right; |
| 7 | + * TreeNode() {} |
| 8 | + * TreeNode(int val) { this.val = val; } |
| 9 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 10 | + * this.val = val; |
| 11 | + * this.left = left; |
| 12 | + * this.right = right; |
| 13 | + * } |
| 14 | + * } |
| 15 | + */ |
| 16 | +class BSTIterator { |
| 17 | + |
| 18 | + private Deque<TreeNode> stack; |
| 19 | + private List<Integer> arr; |
| 20 | + private TreeNode lastNode; |
| 21 | + private int pointer; |
| 22 | + |
| 23 | + public BSTIterator(TreeNode root) { |
| 24 | + this.stack = new ArrayDeque(); |
| 25 | + this.arr = new ArrayList<>(); |
| 26 | + this.lastNode = root; |
| 27 | + this.pointer = -1; |
| 28 | + } |
| 29 | + |
| 30 | + public boolean hasNext() { |
| 31 | + return !this.stack.isEmpty() || lastNode != null || this.pointer < arr.size() - 1; |
| 32 | + } |
| 33 | + |
| 34 | + public int next() { |
| 35 | + this.pointer++; |
| 36 | + if (this.pointer == this.arr.size()) { |
| 37 | + updateStack(lastNode); |
| 38 | + TreeNode curr = this.stack.pop(); |
| 39 | + lastNode = curr.right; |
| 40 | + this.arr.add(curr.val); |
| 41 | + } |
| 42 | + return this.arr.get(this.pointer); |
| 43 | + } |
| 44 | + |
| 45 | + public boolean hasPrev() { |
| 46 | + return this.pointer > 0; |
| 47 | + } |
| 48 | + |
| 49 | + public int prev() { |
| 50 | + this.pointer--; |
| 51 | + return this.arr.get(this.pointer); |
| 52 | + } |
| 53 | + |
| 54 | + private void updateStack(TreeNode node) { |
| 55 | + while (node != null) { |
| 56 | + this.stack.push(node); |
| 57 | + node = node.left; |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Your BSTIterator object will be instantiated and called as such: |
| 64 | + * BSTIterator obj = new BSTIterator(root); |
| 65 | + * boolean param_1 = obj.hasNext(); |
| 66 | + * int param_2 = obj.next(); |
| 67 | + * boolean param_3 = obj.hasPrev(); |
| 68 | + * int param_4 = obj.prev(); |
| 69 | + */ |
0 commit comments