|
| 1 | +/** |
| 2 | + * @typedef {Object} TreeNode |
| 3 | + * @description Definition for a binary tree node. |
| 4 | + * @example |
| 5 | + * function TreeNode(val, left, right) { |
| 6 | + * this.val = (val===undefined ? 0 : val) |
| 7 | + * this.left = (left===undefined ? null : left) |
| 8 | + * this.right = (right===undefined ? null : right) |
| 9 | + * } |
| 10 | + */ |
| 11 | + |
| 12 | +/** |
| 13 | + * Iterator over a binary search tree |
| 14 | + * @summary Binary Search Tree Iterator {@link https://leetcode.com/problems/binary-search-tree-iterator/} |
| 15 | + * @description Given a root node of BST, implement an iterator that returns smallest available number. |
| 16 | + */ |
| 17 | +class BSTIterator { |
| 18 | + constructor(root) { |
| 19 | + this.node = root; |
| 20 | + this.stack = []; |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Space O(1) , Time O(1) |
| 25 | + */ |
| 26 | + hasNext() { |
| 27 | + return this.node || this.stack.length; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Space O(n) - worst case stack will have all nodes. |
| 32 | + * Time O(n) - worst case iterate over all nodes. |
| 33 | + */ |
| 34 | + next() { |
| 35 | + while (this.node) { |
| 36 | + this.stack.push(this.node); |
| 37 | + this.node = this.node.left; |
| 38 | + } |
| 39 | + |
| 40 | + this.node = this.stack.pop(); |
| 41 | + const result = this.node.val; |
| 42 | + this.node = this.node.right; |
| 43 | + |
| 44 | + return result; |
| 45 | + } |
| 46 | +} |
0 commit comments