Skip to content

Commit def3284

Browse files
authored
Create 173-binary-search-tree-iterator.js
1 parent b913502 commit def3284

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

173-binary-search-tree-iterator.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
*/
11+
const BSTIterator = function(root) {
12+
this.root = root;
13+
this.stack = [];
14+
};
15+
16+
/**
17+
* @return the next smallest number
18+
* @return {number}
19+
*/
20+
BSTIterator.prototype.next = function() {
21+
while (this.root) {
22+
this.stack.push(this.root);
23+
this.root = this.root.left;
24+
}
25+
this.root = this.stack.pop();
26+
const result = this.root.val;
27+
this.root = this.root.right;
28+
return result;
29+
};
30+
31+
/**
32+
* @return whether we have a next smallest number
33+
* @return {boolean}
34+
*/
35+
BSTIterator.prototype.hasNext = function() {
36+
return this.root || this.stack.length;
37+
};
38+
39+
/**
40+
* Your BSTIterator object will be instantiated and called as such:
41+
* var obj = new BSTIterator(root)
42+
* var param_1 = obj.next()
43+
* var param_2 = obj.hasNext()
44+
*/
45+

0 commit comments

Comments
 (0)