# LintCode_二叉查找树迭代器

• 元素按照递增的顺序被访问（比如中序遍历）
• next()hasNext()的询问操作要求均摊时间复杂度是O(1)

   10
/    \
1      11
\       \
6       12


/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
* Example of iterate a tree:
* BSTIterator iterator = BSTIterator(root);
* while (iterator.hasNext()) {
*    TreeNode * node = iterator.next();
*    do something for node
*/
class BSTIterator {
public:
//@param root: The root of binary tree.
BSTIterator(TreeNode *root) {
curr=nullptr;
//持续深入左子树
while(root)
{
S.push(root);
root=root->left;
}
}

//@return: True if there has next node, or false
bool hasNext() {
return (S.empty()?false:true);
}

//@return: return next node
TreeNode* next() {
if (S.empty())
{
return NULL;
}
TreeNode *top = S.top(); S.pop(); //先把下一个节点拿出来
if (top->right)  //如果该节点有右子树，则还要处理子树的点
{
TreeNode *cur = top->right;
while (cur)
{
S.push(cur);  //推入栈中去，此时S.front就是下一个结点
cur = cur->left;
}
}

return top;
}
private:
TreeNode* curr;
stack<TreeNode*> S;
};