题目描述:
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(TreeNode *root) {
p=root;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(s.size()>0||p!=NULL) return true;
else return false;
}
/** @return the next smallest number */
int next() {
while(p!=NULL)
{
s.push(p);
p=p->left;
}
int result=0;
if(s.size()>0)
{
p=s.top();
result=p->val;
s.pop();
p=p->right;
}
return result;
}
private:
TreeNode* p;
stack<TreeNode*> s;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/