1. Precomputed Inorder Array
Intuition
Run a full inorder traversal in the constructor and store all N node values in a list. Maintain an index pointer pointing to the current element. hasNext() checks idx < list.size(), and next() returns list[idx++].
When to apply: Simple baseline when O(N) memory is acceptable.
Algorithm
- Step 1: Traverse tree inorder, storing values in list.
- Step 2: Initialize index pointer
idx = 0. - Step 3:
hasNext()returnsidx < list.size(). - Step 4:
next()returnslist[idx++].
#include <iostream>#include <vector>using namespace std; struct TreeNode { int val; TreeNode *left, *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class BSTIterator { vector<int> vals; int idx = 0; void inorder(TreeNode* node) { if (!node) return; inorder(node->left); vals.push_back(node->val); inorder(node->right); }public: BSTIterator(TreeNode* root) { inorder(root); } int next() { return vals[idx++]; } bool hasNext() { return idx < vals.size(); }}; int main() { TreeNode* root = new TreeNode(7); root->left = new TreeNode(3); root->right = new TreeNode(15); BSTIterator it(root); cout << it.next() << " " << it.next() << " " << boolalpha << it.hasNext() << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) constructor, O(1) next() and hasNext() - Space complexity:
O(N) memory