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.
实施一个二叉搜索树的迭代器,包含hasNext()和next()两个函数,hasNext()判断是否有下一节点,next()返回节点元素值。遍历顺序按照元素递增方式。
利用二叉搜索树的左<根<右的性质,用中序遍历就可得到从小到大的所有节点。
最小的元素自然是从root开始一直找左子树左子树直到为空,找到了第一个元素,但是接下来的元素怎么办呢?Binary Search Tree又没有回退的指针,所以要采取某种方法记录一路寻找下来的路径上的元素,可以采用Stack,它具有后进先出的功能,符合要求。把从root到最小元素的一路的左子树元素存储到stack里,对于next()函数,第一步需要做的就是把栈顶的元素pop出来,这就是需要找的元素,同时还要修改指针,使得指针指向下一个需要pop的元素。这里遇到一个问题,如果当前元素的右子树不为空,那么下一个元素就是它右子树中左子树左子树....的最小元素,同样也需要在down to leaf的过程中,把一路上的元素加入到Stack中。根据Binary Search Tree的性质,某个结点的右子树中的所有元素都是小于当前结点的父节点的元素的。对于hasNext()函数,只要检查Stack是否为空就行。
Java:
public class BSTIterator {
Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
while(root != null) {
stack.add(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode temp = stack.pop();
int val = temp.val;
if(temp.right != null) {
temp = temp.right;
while (temp != null) {
stack.add(temp);
temp = temp.left;
}
}
return val;
}
}
Java:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
private Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
pushAll(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode curr = stack.pop();
pushAll(curr.right);
return curr.val;
}
private void pushAll(TreeNode node){
TreeNode curr = node;
while(curr != null){
stack.push(curr);
curr = curr.left;
}
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
Python:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BSTIterator:
# @param root, a binary search tree's root node
def __init__(self, root):
self.stack = []
self.cur = root
# @return a boolean, whether we have a next smallest number
def hasNext(self):
return self.stack or self.cur
# @return an integer, the next smallest number
def next(self):
while self.cur:
self.stack.append(self.cur)
self.cur = self.cur.left
self.cur = self.stack.pop()
node = self.cur
self.cur = self.cur.right
return node.val
Python:
class BSTIterator:
# @param root, a binary search tree's root node
def __init__(self, root):
self.stack = list()
self.pushAll(root)
# @return a boolean, whether we have a next smallest number
def hasNext(self):
return self.stack
# @return an integer, the next smallest number
def next(self):
tmpNode = self.stack.pop()
self.pushAll(tmpNode.right)
return tmpNode.val
def pushAll(self, node):
while node is not None:
self.stack.append(node)
node = node.left
C++:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
while (root) {
s.push(root);
root = root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !s.empty();
}
/** @return the next smallest number */
int next() {
TreeNode *n = s.top();
s.pop();
int res = n->val;
if (n->right) {
n = n->right;
while (n) {
s.push(n);
n = n->left;
}
}
return res;
}
private:
stack<TreeNode*> s;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/