Created
July 3, 2020 00:37
-
-
Save RP-3/daf9aecd480d3c957081d7b3ea7dec19 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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