|
| 1 | +/** |
| 2 | + * 173. Binary Search Tree Iterator |
| 3 | + * https://leetcode.com/problems/binary-search-tree-iterator/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Implement the BSTIterator class that represents an iterator over the in-order traversal |
| 7 | + * of a binary search tree (BST): |
| 8 | + * - BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of |
| 9 | + * the BST is given as part of the constructor. The pointer should be initialized to a |
| 10 | + * non-existent number smaller than any element in the BST. |
| 11 | + * - boolean hasNext() Returns true if there exists a number in the traversal to the right |
| 12 | + * of the pointer, otherwise returns false. |
| 13 | + * - int next() Moves the pointer to the right, then returns the number at the pointer. |
| 14 | + * |
| 15 | + * Notice that by initializing the pointer to a non-existent smallest number, the first call |
| 16 | + * to next() will return the smallest element in the BST. |
| 17 | + * |
| 18 | + * You may assume that next() calls will always be valid. That is, there will be at least a |
| 19 | + * next number in the in-order traversal when next() is called. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * Definition for a binary tree node. |
| 24 | + * function TreeNode(val, left, right) { |
| 25 | + * this.val = (val===undefined ? 0 : val) |
| 26 | + * this.left = (left===undefined ? null : left) |
| 27 | + * this.right = (right===undefined ? null : right) |
| 28 | + * } |
| 29 | + */ |
| 30 | +/** |
| 31 | + * @param {TreeNode} root |
| 32 | + */ |
| 33 | +var BSTIterator = function(root) { |
| 34 | + this.stack = []; |
| 35 | + this.root = root; |
| 36 | +}; |
| 37 | + |
| 38 | +/** |
| 39 | + * @return {number} |
| 40 | + */ |
| 41 | +BSTIterator.prototype.next = function() { |
| 42 | + while (this.root) { |
| 43 | + this.stack.push(this.root); |
| 44 | + this.root = this.root.left; |
| 45 | + } |
| 46 | + this.root = this.stack.pop(); |
| 47 | + |
| 48 | + const result = this.root.val; |
| 49 | + this.root = this.root.right; |
| 50 | + return result; |
| 51 | +}; |
| 52 | + |
| 53 | +/** |
| 54 | + * @return {boolean} |
| 55 | + */ |
| 56 | +BSTIterator.prototype.hasNext = function() { |
| 57 | + return this.root || this.stack.length; |
| 58 | +}; |
0 commit comments