-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0173-binary-search-tree-iterator.js
61 lines (54 loc) · 1.46 KB
/
0173-binary-search-tree-iterator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* Controlled Recursion - Average Time (1)
* Time O(N) | Space O(N)
* https://leetcode.com/problems/binary-search-tree-iterator/
* @param {TreeNode} root
*/
class BSTIterator {
constructor (root) {
this.stack = []; /* | Space O(N) */
this.getLeft(root);/* Time O(N) | Space O(N)*/
}
/**
* Time O(N) | Space O(H)
* @return {number}
*/
getLeft (root, { stack } = this) {
while (root !== null) {/* Time O(N) */
stack.push(root); /* Space O(N) */
root = root.left;
}
}
/**
* Time O(N) | Space O(N)
* @return the next smallest number
* @return {number}
*/
next ({ stack } = this) {
const node = stack.pop();
if (node.right) this.getLeft(node.right);/* Time O(N) | Space O(N) */
return node.val;
};
/**
* Time O(1) | Space O(1)
* @return whether we have a next smallest number
* @return {boolean}
*/
hasNext ({ stack } = this) {
return (stack.length !== 0);
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* var obj = new BSTIterator(root)
* var param_1 = obj.next()
* var param_2 = obj.hasNext()
*/