这题本质上就是二叉树的中序遍历,next()用来输出当前值,hasnext()来判断是否为最后一个元素。注意这题要求O(1)的时间复杂度与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 Solution {
public:
stack<TreeNode*> stk;
vector<int> ans;
vector<int> inorderTraversal(TreeNode* root) {
while(root || stk.size()) {
while (root) {
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
ans.push_back(root->val);
root = root->right;
}
return ans;
}
};
这里的进栈出栈的次数为n,时间复杂度为O(n),空间复杂度为栈用到的长度,栈本质就是一条链,最长时,即为树的高度h,空间复杂度为O(h)。
下面的结果时间复杂度为1,因为最多装n个元素的情况下,最多可以使用next()次数为n - 1次,平均下来时间复杂度应为O(n / (n - 1))即为常数时间复杂度。
代码
/**
* 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:
stack<TreeNode*>stk;
BSTIterator(TreeNode* root) {
while (root) {
stk.push(root);
root = root->left;
}
}
int next() {
auto root = stk.top();
stk.pop();
int val = root->val;
root = root->right;
while(root) {
stk.push(root);
root = root->left;
}
return val;
}
bool hasNext() {
return stk.size();
}
};
/**
* 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();
*/