赞
踩
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: BSTIterator(TreeNode* root) { } int next() { } bool hasNext() { } };
这道题本质上考的是「将迭代版的中序遍历代码」做等价拆分。
next
节点我们来看个具体的例子,实际访问节点的顺序是:
根据上面的遍历顺序,我们得出迭代的思路:
cpp
class BSTIterator { std::stack<TreeNode *>stack; void leftmostInOrder(TreeNode *root){ while (root != NULL){ stack.push(root); root = root->left; } } public: BSTIterator(TreeNode* root) { leftmostInOrder(root); } int next() { TreeNode *pop = stack.top(); stack.pop(); if (pop->right != NULL){ leftmostInOrder(pop->right); } return pop->val; } bool hasNext() { return stack.size() != 0; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。