https://leetcode.com/problems/binary-search-tree-iterator/description/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BSTIterator {
public:
stack<TreeNode*> st;
BSTIterator(TreeNode *root) {
TreeNode* p = root;
while (p) {
st.push(p);
p = p->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !st.empty();
}
/** @return the next smallest number */
int next() {
TreeNode *cur = st.top();
st.pop();
int v = cur->val;
cur = cur->right;
while (cur) {
st.push(cur);
cur = cur->left;
}
return v;
}
};