@@ -65,3 +65,76 @@ function helper(node, res) {
65
65
* var param_3 = obj.hasPrev()
66
66
* var param_4 = obj.prev()
67
67
*/
68
+
69
+ // another
70
+
71
+ /**
72
+ * Definition for a binary tree node.
73
+ * function TreeNode(val, left, right) {
74
+ * this.val = (val===undefined ? 0 : val)
75
+ * this.left = (left===undefined ? null : left)
76
+ * this.right = (right===undefined ? null : right)
77
+ * }
78
+ */
79
+ /**
80
+ * @param {TreeNode } root
81
+ */
82
+ const BSTIterator = function ( root ) {
83
+ this . nums = [ ]
84
+ this . stack = [ ]
85
+ this . node = root
86
+ this . i = 0 // pointer to next node
87
+ this . size = 0
88
+ }
89
+
90
+ /**
91
+ * @return {boolean }
92
+ */
93
+ BSTIterator . prototype . hasNext = function ( ) {
94
+ return this . i < this . size || this . stack . length > 0 || ! ! this . node
95
+ }
96
+
97
+ /**
98
+ * @return {number }
99
+ */
100
+ BSTIterator . prototype . next = function ( ) {
101
+ if ( this . i < this . size ) return this . nums [ this . i ++ ]
102
+ if ( this . stack . length || this . node ) {
103
+ while ( this . node ) {
104
+ this . stack . push ( this . node )
105
+ this . node = this . node . left
106
+ }
107
+ this . node = this . stack . pop ( )
108
+ this . i += 1
109
+ this . size += 1
110
+ const val = this . node . val
111
+ this . nums . push ( val )
112
+ this . node = this . node . right
113
+ return val
114
+ }
115
+ return - 1
116
+ }
117
+
118
+ /**
119
+ * @return {boolean }
120
+ */
121
+ BSTIterator . prototype . hasPrev = function ( ) {
122
+ return this . i - 2 >= 0
123
+ }
124
+
125
+ /**
126
+ * @return {number }
127
+ */
128
+ BSTIterator . prototype . prev = function ( ) {
129
+ return this . nums [ -- this . i - 1 ]
130
+ }
131
+
132
+ /**
133
+ * Your BSTIterator object will be instantiated and called as such:
134
+ * var obj = new BSTIterator(root)
135
+ * var param_1 = obj.hasNext()
136
+ * var param_2 = obj.next()
137
+ * var param_3 = obj.hasPrev()
138
+ * var param_4 = obj.prev()
139
+ */
140
+
0 commit comments