/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classBSTIterator { private: queue<int> q;
voidinOrder(TreeNode* root) { if (!root) return; inOrder(root->left); q.push(root->val); inOrder(root->right); }
public: BSTIterator(TreeNode* root) { inOrder(root); } /** @return the next smallest number */ intnext() { auto front = q.front(); q.pop(); return front; } /** @return whether we have a next smallest number */ boolhasNext() { return !q.empty(); } };
/** * 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(); */
classBSTIterator{ Stack<TreeNode> stack = new Stack<>(); TreeNode cur = null;
publicBSTIterator(TreeNode root){ cur = root; }
/** @return the next smallest number */ publicintnext(){ int res = -1; while (cur != null || !stack.isEmpty()) { // 节点不为空一直压栈 while (cur != null) { stack.push(cur); cur = cur.left; // 考虑左子树 } // 节点为空,就出栈 cur = stack.pop(); res = cur.val; // 考虑右子树 cur = cur.right; break; }
return res; }
/** @return whether we have a next smallest number */ publicbooleanhasNext(){ return cur != null || !stack.isEmpty(); } }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classBSTIterator { private: stack<TreeNode*> s; TreeNode* cur = nullptr; public: BSTIterator(TreeNode* root) { cur = root; } /** @return the next smallest number */ intnext() { int res = -1; while (cur || !s.empty()) { while (cur != nullptr) { s.push(cur); cur = cur->left; }
cur = s.top(); s.pop(); res = cur->val;
cur = cur->right; break; }
return res; } /** @return whether we have a next smallest number */ boolhasNext(){ return cur || !s.empty(); } };
/** * 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(); */