题目:

image.png
image.png


个人解答:
采用Vector记录二叉树中序输出,利用vector来判断是否有下个值及输出下个值。

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class BSTIterator {
  13. int cur = 1;
  14. std::vector<int> nodes = {-1};
  15. public:
  16. BSTIterator(TreeNode* root) {
  17. if(!root->left&&!root->right)
  18. {
  19. nodes.push_back(root->val);
  20. }
  21. else
  22. in_travelsal(root);
  23. }
  24. int next() {
  25. int value = nodes[cur];
  26. if(cur<nodes.size())
  27. {
  28. cur++;
  29. }
  30. return value;
  31. }
  32. bool hasNext() {
  33. if(cur < nodes.size())
  34. return true;
  35. else
  36. return false;
  37. }
  38. void in_travelsal(TreeNode* root)
  39. {
  40. std::stack<TreeNode*> stack_node;
  41. while(root!=nullptr || !stack_node.empty())
  42. {
  43. if(root!=nullptr)
  44. {
  45. stack_node.push(root);
  46. root = root->left;
  47. }
  48. else
  49. {
  50. root = stack_node.top();
  51. nodes.push_back(root->val);
  52. stack_node.pop();
  53. root = root -> right;
  54. }
  55. }
  56. }
  57. };
  58. /**
  59. * Your BSTIterator object will be instantiated and called as such:
  60. * BSTIterator* obj = new BSTIterator(root);
  61. * int param_1 = obj->next();
  62. * bool param_2 = obj->hasNext();
  63. */

官方解答:

方法一:扁平化

我们可以直接对二叉搜索树做一次完全的递归遍历,获取中序遍历的全部结果并保存在数组中。随后,我们利用得到的数组本身来实现迭代器。

  1. class BSTIterator {
  2. private:
  3. void inorder(TreeNode* root, vector<int>& res) {
  4. if (!root) {
  5. return;
  6. }
  7. inorder(root->left, res);
  8. res.push_back(root->val);
  9. inorder(root->right, res);
  10. }
  11. vector<int> inorderTraversal(TreeNode* root) {
  12. vector<int> res;
  13. inorder(root, res);
  14. return res;
  15. }
  16. vector<int> arr;
  17. int idx;
  18. public:
  19. BSTIterator(TreeNode* root): idx(0), arr(inorderTraversal(root)) {}
  20. int next() {
  21. return arr[idx++];
  22. }
  23. bool hasNext() {
  24. return (idx < arr.size());
  25. }
  26. };

image.png


方法二:迭代

除了递归的方法外,我们还可以利用栈这一数据结构,通过迭代的方式对二叉树做中序遍历。此时,我们无需预先计算出中序遍历的全部结果,只需要实时维护当前栈的情况即可。

  1. class BSTIterator {
  2. private:
  3. TreeNode* cur;
  4. stack<TreeNode*> stk;
  5. public:
  6. BSTIterator(TreeNode* root): cur(root) {}
  7. int next() {
  8. while (cur != nullptr) {
  9. stk.push(cur);
  10. cur = cur->left;
  11. }
  12. cur = stk.top();
  13. stk.pop();
  14. int ret = cur->val;
  15. cur = cur->right;
  16. return ret;
  17. }
  18. bool hasNext() {
  19. return cur != nullptr || !stk.empty();
  20. }
  21. };

image.png