Binary Search Tree Iterator
1) Use inorder traversal (non-recursion);
2) Please remember inorder non-recursion traversal;
code
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
vector<TreeNode*> stack;
TreeNode* p;
BSTIterator(TreeNode *root) {
p = root;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(p != NULL || !stack.empty())
{
return true;
}
else
{
return false;
}
}
/** @return the next smallest number */
int next() {
while(p != NULL)
{
stack.push_back(p);
p = p->left;
}
p = stack.back();
stack.pop_back();
int ret = p->val;
p = p->right;
return ret;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/