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