Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created July 3, 2020 00:37
Show Gist options
  • Save RP-3/daf9aecd480d3c957081d7b3ea7dec19 to your computer and use it in GitHub Desktop.
Save RP-3/daf9aecd480d3c957081d7b3ea7dec19 to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
*/
var BSTIterator = function(root) {
this.stack = [];
this.fillStackFromNode(root);
};
BSTIterator.prototype.fillStackFromNode = function(node){
if(!node) return;
this.stack.push(node);
this.fillStackFromNode(node.left);
}
/**
* @return the next smallest number
* @return {number}
*/
BSTIterator.prototype.next = function() {
const rtn = this.stack.pop();
this.fillStackFromNode(rtn.right);
return rtn.val;
};
/**
* @return whether we have a next smallest number
* @return {boolean}
*/
BSTIterator.prototype.hasNext = function() {
return this.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()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment