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.
思路:依靠栈数据结构,然后中序遍历的思想
class BSTIterator {
public:
BSTIterator(BinTree *root) {
while(!st.empty())
sk.pop();
BinTree* temp=root;
while(temp != NULL)
{
sk.push(temp);
temp = temp->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return sk.empty();
}
/** @return the next smallest number */
int next() {
BinTree* res = sk.top();
sk.pop();
BinTree* temp = res->right;
while(temp != NULL)
{
sk.push(temp);
temp = temp->left;
}
return res->value;
}
private:
stack<BinTree*> sk;
};
Binary Search Tree Iterator--LeetCode
原文:http://blog.csdn.net/yusiguyuan/article/details/45039669