# Binary Search Tree Iterator

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.

# 解题思路：

## 方法：

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
stack<TreeNode*> qu;
public:
BSTIterator(TreeNode *root) {
push_in_stack(root);
}

/** @return whether we have a next smallest number */
bool hasNext() {
return !qu.empty();

}

/** @return the next smallest number */
int next() {
TreeNode *tmpNode = qu.top();
qu.pop();
push_in_stack(tmpNode->right);
return tmpNode->val;
}
private:
void push_in_stack(TreeNode* node)
{
while(node)
{
qu.push(node);
node=node->left;
}
}
};

/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/

while (i.hasNext()) cout << i.next();

• 本文已收录于以下专栏：

举报原因： 您举报文章：Binary Search Tree Iterator 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)