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.
本题的题意理解的并不是很明白:
代码参考链接:http://blog.csdn.net/efergrehbtrj/article/details/45838637
整体思:
第一步:首先在类的构造函数中,将用根节点开始的所有的左孩子全部压入栈中,那么此时栈顶的一定是最小元素—BSTIterator(TreeNode *root)完成的功能;
第二步:next()函数是用来取得下一个最小值得,由知道栈顶的一定是最小元素,但是下一个最小元素就不一定了,根据二叉搜索树的性质可知,下一个最小的元素要么是栈顶元素的父节点,要么是栈顶元素的右孩子的最有节点,故而next()函数实现的过程如下;
此外,hasNext函数知识用来判断是不是含有下一个最小元素的。
代码一、相当于采用中序遍历,由于基于二叉搜索树的性质
class BSTIterator {
stack<TreeNode *> myStack;
public:
BSTIterator(TreeNode *root) {
pushAll(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !myStack.empty();
}
/** @return the next smallest number */
int next() {
TreeNode *tmpNode = myStack.top();
myStack.pop();
pushAll(tmpNode->right);
return tmpNode->val;
}
private:
void pushAll(TreeNode *node) {
for (; node != NULL; myStack.push(node), node = node->left);
}
};
代码二、
class BSTIterator {
private:
stack<TreeNode*> st;
public:
BSTIterator(TreeNode *root) {
find_left(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
if (st.empty())
return false;
return true;
}
/** @return the next smallest number */
int next() {
TreeNode* top = st.top();
st.pop();
if (top->right != NULL)
find_left(top->right);
return top->val;
}
/** put all the left child() of root */
void find_left(TreeNode* root)
{
TreeNode* p = root;
while (p != NULL)
{
st.push(p);
p = p->left;
}
}
};
代码三、
class BSTIterator {
private:
stack<TreeNode*> sta;
public:
BSTIterator(TreeNode *root) {
findLeft(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !sta.empty();
}
/** @return the next smallest number */
int next() {
TreeNode *top = sta.top();
sta.pop();
if(top->right != NULL)
findLeft(top->right);
return top->val;
}
/** put all the left child() of root */
void findLeft(TreeNode *node)
{
while(node!=NULL)
{
sta.push(node);
node = node->left;
}
}
};