Note:
跟中序遍历的迭代写法一样,自己去维护一个栈
hasNext的时候就看看当前指针是不是空,或者栈是不是空就行了
cur指向的就是下一个需要判断的分支位置
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class BSTIterator {
public:
TreeNode* cur;
stack<TreeNode*> s;
BSTIterator(TreeNode* root) {
cur = root;
}
int next() {
while(cur != NULL){
s.push(cur);
cur = cur -> left;
}
cur = s.top();
s.pop();
int a = cur -> val;
cur = cur -> right;
return a;
}
bool hasNext() {
return cur || !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();
*/