二叉搜索树迭代器 考了几个知识点:1. 二叉搜索树迭代器 2. 迭代器。
难点就是O1的时间复杂度以及Oh 的空间复杂度。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
stack<TreeNode* > s;
public:
BSTIterator(TreeNode* root) {
TreeNode* current = root;
while(current){
s.push(current);
current = current->left;
}
}
/** @return the next smallest number */
int next() {
TreeNode* top_current = s.top(); s.pop();
int current = top_current->val;
top_current = top_current->right;
while(top_current){
s.push(top_current);
top_current = top_current->left;
}
return current;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !s.empty();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/