leetcode每日一题-173. Binary Search Tree Iterator
1.先dfs,保存dfs的所有值的o(n)做法
/**
* 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:
int node[100003];
int cnt=0;
int idx=0;
void dfs(TreeNode* u){
if(u==nullptr) return;
dfs(u->left);
node[cnt++]=u->val;
dfs(u->right);
}
BSTIterator(TreeNode* root) {
memset(node,0,sizeof node);
dfs(root);
}
int next() {
//dfs的下个结点
return node[idx++];
}
bool hasNext() {
//只要不是最后一个结点全为true
if(idx!=cnt) return true;
else return false;
}
};
/**
* 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();
*/
2.维护递归栈的做法 o(h)
/**
* 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 {
private:
TreeNode* cur;
stack<TreeNode*> stk;
public:
BSTIterator(TreeNode* root) {
cur=root;
}
int next() {
while(cur!=nullptr){//将cur左边的全部进栈
stk.push(cur);
cur=cur->left;
}
cur=stk.top();
stk.pop();
int ret=cur->val;
cur=cur->right;
return ret;
}
bool hasNext() {
if(cur!=nullptr || !stk.empty()) return true;
return false;
}
};
/**
* 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();
*/