Skip to content

Instantly share code, notes, and snippets.

@basekays
Last active June 19, 2018 23:14
Show Gist options
  • Select an option

  • Save basekays/345c8cb185e04322744e96198ed7393f to your computer and use it in GitHub Desktop.

Select an option

Save basekays/345c8cb185e04322744e96198ed7393f to your computer and use it in GitHub Desktop.
/**
* Definition for binary tree
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @constructor
* @param {TreeNode} root - root of the binary search tree
*/
var BSTIterator = function(root) {
this.stack = [];
while(root) {
this.stack.push(root);
root = root.left;
}
};
BSTIterator.prototype.hasNext = function() {
return this.stack.length != 0;
};
BSTIterator.prototype.next = function() {
let subTreeRoot = this.stack.pop();
let nextVal = subTreeRoot.val;
subTreeRoot = subTreeRoot.right;
while(subTreeRoot) {
this.stack.push(subTreeRoot);
subTreeRoot = subTreeRoot.left;
}
return nextVal;
};
/*
* Your BSTIterator will be called like this:
* var i = new BSTIterator(root), a = [];
* while (i.hasNext()) a.push(i.next());
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment