题目:


个人解答:
采用Vector记录二叉树中序输出,利用vector来判断是否有下个值及输出下个值。
/*** 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 {int cur = 1;std::vector<int> nodes = {-1};public:BSTIterator(TreeNode* root) {if(!root->left&&!root->right){nodes.push_back(root->val);}elsein_travelsal(root);}int next() {int value = nodes[cur];if(cur<nodes.size()){cur++;}return value;}bool hasNext() {if(cur < nodes.size())return true;elsereturn false;}void in_travelsal(TreeNode* root){std::stack<TreeNode*> stack_node;while(root!=nullptr || !stack_node.empty()){if(root!=nullptr){stack_node.push(root);root = root->left;}else{root = stack_node.top();nodes.push_back(root->val);stack_node.pop();root = root -> right;}}}};/*** 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();*/
官方解答:
方法一:扁平化
我们可以直接对二叉搜索树做一次完全的递归遍历,获取中序遍历的全部结果并保存在数组中。随后,我们利用得到的数组本身来实现迭代器。
class BSTIterator {private:void inorder(TreeNode* root, vector<int>& res) {if (!root) {return;}inorder(root->left, res);res.push_back(root->val);inorder(root->right, res);}vector<int> inorderTraversal(TreeNode* root) {vector<int> res;inorder(root, res);return res;}vector<int> arr;int idx;public:BSTIterator(TreeNode* root): idx(0), arr(inorderTraversal(root)) {}int next() {return arr[idx++];}bool hasNext() {return (idx < arr.size());}};

方法二:迭代
除了递归的方法外,我们还可以利用栈这一数据结构,通过迭代的方式对二叉树做中序遍历。此时,我们无需预先计算出中序遍历的全部结果,只需要实时维护当前栈的情况即可。
class BSTIterator {private:TreeNode* cur;stack<TreeNode*> stk;public:BSTIterator(TreeNode* root): cur(root) {}int next() {while (cur != nullptr) {stk.push(cur);cur = cur->left;}cur = stk.top();stk.pop();int ret = cur->val;cur = cur->right;return ret;}bool hasNext() {return cur != nullptr || !stk.empty();}};

