Problem
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next()
will return the next smallest number in the BST.
Note: next()
and hasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Credits:Special thanks to @ts for adding this problem and creating all test cases.
Solution (Java)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class BSTIterator {
private TreeNode node;
public BSTIterator(TreeNode root) {
node = root;
}
public int next() {
int res = -1;
while (node != null) {
if (node.left != null) {
TreeNode rightMost = node.left;
while (rightMost.right != null) {
rightMost = rightMost.right;
}
rightMost.right = node;
TreeNode temp = node.left;
node.left = null;
node = temp;
} else {
res = node.val;
node = node.right;
return res;
}
}
return res;
}
public boolean hasNext() {
return node != null;
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
Solution (Javascript)
/**
* 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 = [];
this.pushAll(root);
};
/**
* @this BSTIterator
* @returns {boolean} - whether we have a next smallest number
*/
BSTIterator.prototype.hasNext = function() {
return this.stack.length !== 0;
};
/**
* @this BSTIterator
* @returns {number} - the next smallest number
*/
BSTIterator.prototype.next = function() {
var node = this.stack.pop();
this.pushAll(node.right);
return node.val;
};
/**
* Your BSTIterator will be called like this:
* var i = new BSTIterator(root), a = [];
* while (i.hasNext()) a.push(i.next());
*/
BSTIterator.prototype.pushAll = function (node) {
while (node) {
this.stack.push(node);
node = node.left;
}
};
Explain:
nope.
Complexity:
- Time complexity :
- Space complexity :