Skip to content

Commit 6021aec

Browse files
authored
Create 1586-binary-search-tree-iterator-ii.js
1 parent ec066c1 commit 6021aec

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
*/
12+
const BSTIterator = function(root) {
13+
this.r = root
14+
const ans = []
15+
helper(root, ans)
16+
this.arr = ans
17+
this.cur = -1
18+
};
19+
20+
/**
21+
* @return {boolean}
22+
*/
23+
BSTIterator.prototype.hasNext = function() {
24+
return this.arr.length && this.cur < this.arr.length - 1
25+
};
26+
27+
/**
28+
* @return {number}
29+
*/
30+
BSTIterator.prototype.next = function() {
31+
this.cur += 1
32+
return this.arr[this.cur]
33+
};
34+
35+
/**
36+
* @return {boolean}
37+
*/
38+
BSTIterator.prototype.hasPrev = function() {
39+
return this.arr.length && this.cur > 0
40+
};
41+
42+
/**
43+
* @return {number}
44+
*/
45+
BSTIterator.prototype.prev = function() {
46+
return this.arr[--this.cur]
47+
};
48+
49+
function helper(node, res) {
50+
if(node == null) return
51+
if(node.left) {
52+
helper(node.left, res)
53+
}
54+
res.push(node.val)
55+
if(node.right) {
56+
helper(node.right, res)
57+
}
58+
}
59+
60+
/**
61+
* Your BSTIterator object will be instantiated and called as such:
62+
* var obj = new BSTIterator(root)
63+
* var param_1 = obj.hasNext()
64+
* var param_2 = obj.next()
65+
* var param_3 = obj.hasPrev()
66+
* var param_4 = obj.prev()
67+
*/

0 commit comments

Comments
 (0)