|
| 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 | +classBSTIterator { |
| 17 | + |
| 18 | +privateDeque<TreeNode>stack; |
| 19 | +privateList<Integer>arr; |
| 20 | +privateTreeNodelastNode; |
| 21 | +privateintpointer; |
| 22 | + |
| 23 | +publicBSTIterator(TreeNoderoot) { |
| 24 | +this.stack =newArrayDeque(); |
| 25 | +this.arr =newArrayList<>(); |
| 26 | +this.lastNode =root; |
| 27 | +this.pointer = -1; |
| 28 | + } |
| 29 | + |
| 30 | +publicbooleanhasNext() { |
| 31 | +return !this.stack.isEmpty() ||lastNode !=null ||this.pointer <arr.size() -1; |
| 32 | + } |
| 33 | + |
| 34 | +publicintnext() { |
| 35 | +this.pointer++; |
| 36 | +if (this.pointer ==this.arr.size()) { |
| 37 | +updateStack(lastNode); |
| 38 | +TreeNodecurr =this.stack.pop(); |
| 39 | +lastNode =curr.right; |
| 40 | +this.arr.add(curr.val); |
| 41 | + } |
| 42 | +returnthis.arr.get(this.pointer); |
| 43 | + } |
| 44 | + |
| 45 | +publicbooleanhasPrev() { |
| 46 | +returnthis.pointer >0; |
| 47 | + } |
| 48 | + |
| 49 | +publicintprev() { |
| 50 | +this.pointer--; |
| 51 | +returnthis.arr.get(this.pointer); |
| 52 | + } |
| 53 | + |
| 54 | +privatevoidupdateStack(TreeNodenode) { |
| 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 | + */ |