-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0173_binarySearchTreeIterator.js
46 lines (41 loc) · 1.08 KB
/
0173_binarySearchTreeIterator.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
/**
* @typedef {Object} TreeNode
* @description Definition for a binary tree node.
* @example
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* Iterator over a binary search tree
* @summary Binary Search Tree Iterator {@link https://leetcode.com/problems/binary-search-tree-iterator/}
* @description Given a root node of BST, implement an iterator that returns smallest available number.
*/
class BSTIterator {
constructor(root) {
this.node = root;
this.stack = [];
}
/**
* Space O(1) , Time O(1)
*/
hasNext() {
return this.node || this.stack.length;
}
/**
* Space O(n) - worst case stack will have all nodes.
* Time O(n) - worst case iterate over all nodes.
*/
next() {
while (this.node) {
this.stack.push(this.node);
this.node = this.node.left;
}
this.node = this.stack.pop();
const result = this.node.val;
this.node = this.node.right;
return result;
}
}