Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root) - Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
boolean hasNext() - Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
int next() - Moves the pointer to the right, then returns the number at the pointer.
boolean hasPrev() - Returns true if there exists a number in the traversal to the left of the pointer, otherwise returns false.
int prev() - Moves the pointer to the left, then returns the number at the pointer.
Notice: By initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. You may assume that next() and prev() calls will always be valid.
💡 Note:Initialize iterator with BST [7,3,15,null,null,9,20]. In-order traversal: 3,7,9,15,20. Iterator starts before first element, so first next() returns 3, then 7, then 9. At this point hasPrev() returns true since we can go back, and prev() returns 7.
💡 Note:Single node BST. hasNext() is true initially, next() returns 5. After consuming the only element, hasPrev() is false (started before first element) and hasNext() is false.
Constraints
The number of nodes in the tree is in the range [1, 105]
0 ≤ Node.val ≤ 106
At most 105 calls will be made to hasNext, next, hasPrev, and prev
The key insight is to use two stacks to efficiently track predecessors and successors for bidirectional navigation. The two-stack approach provides O(1) amortized time complexity while using only O(h) space where h is tree height. Time: O(1) amortized, Space: O(h).
Common Approaches
✓
Precompute All Values
⏱️ Time: O(n)
Space: O(n)
Perform complete in-order traversal during initialization and store all values in an array. Use an index pointer to track current position and implement navigation methods using array indexing.
Two-Stack Approach
⏱️ Time: O(1)
Space: O(h)
Maintain two stacks: one for tracking the path to predecessors (smaller values) and another for successors (larger values). This allows for O(1) amortized time for navigation operations while using O(h) space where h is tree height.
Precompute All Values — Algorithm Steps
Step 1: Traverse BST in-order and store all values in array
Step 2: Maintain current index pointer starting at -1
Step 3: Implement methods using simple array access and bounds checking
Visualization
Tap to expand
Step-by-Step Walkthrough
1
In-Order Traversal
Visit all nodes: left subtree, root, right subtree
2
Store in Array
Collect values: [3, 7, 9, 15, 20]
3
Navigate with Index
Use index pointer for bidirectional movement
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
// --- Tree and Iterator structures remain the same ---
typedef struct TreeNode {
int val;
struct TreeNode *left, *right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
typedef struct {
int* values;
int size;
int index;
} BSTIterator;
void inorder(TreeNode* root, int** values, int* size, int* capacity) {
if (!root) return;
inorder(root->left, values, size, capacity);
if (*size >= *capacity) {
*capacity *= 2;
*values = (int*)realloc(*values, sizeof(int) * (*capacity));
}
(*values)[(*size)++] = root->val;
inorder(root->right, values, size, capacity);
}
BSTIterator* createIterator(TreeNode* root) {
BSTIterator* it = (BSTIterator*)malloc(sizeof(BSTIterator));
int capacity = 10;
it->values = (int*)malloc(sizeof(int) * capacity);
it->size = 0;
it->index = -1;
inorder(root, &(it->values), &(it->size), &capacity);
return it;
}
// --- Helper to clean tokens (Removes brackets and commas) ---
void cleanToken(char* s) {
char* src = s;
char* dst = s;
while (*src) {
if (isdigit(*src) || *src == '-' || isalpha(*src)) {
*dst++ = *src;
}
src++;
}
*dst = '\0';
}
TreeNode* buildTree(char** nodes, int count) {
if (count == 0 || strcmp(nodes[0], "null") == 0 || strlen(nodes[0]) == 0) return NULL;
TreeNode* root = createNode(atoi(nodes[0]));
TreeNode** queue = (TreeNode**)malloc(sizeof(TreeNode*) * (count + 1));
int head = 0, tail = 0;
queue[tail++] = root;
int i = 1;
while (head < tail && i < count) {
TreeNode* curr = queue[head++];
// Left Child
if (i < count && strcmp(nodes[i], "null") != 0 && strlen(nodes[i]) > 0) {
curr->left = createNode(atoi(nodes[i]));
queue[tail++] = curr->left;
}
i++;
// Right Child
if (i < count && strcmp(nodes[i], "null") != 0 && strlen(nodes[i]) > 0) {
curr->right = createNode(atoi(nodes[i]));
queue[tail++] = curr->right;
}
i++;
}
free(queue);
return root;
}
int main() {
char cmdLine[4096], inputLine[4096];
if (!fgets(cmdLine, sizeof(cmdLine), stdin)) return 0;
if (!fgets(inputLine, sizeof(inputLine), stdin)) return 0;
// 1. Parse Commands
char* commands[200];
int cmdCount = 0;
char* cmdToken = strtok(cmdLine, " \",[]\n");
while (cmdToken) {
commands[cmdCount++] = strdup(cmdToken);
cmdToken = strtok(NULL, " \",[]\n");
}
// 2. Parse Tree Array (Targeting the first nested array)
char* treeNodes[200];
int nodeCount = 0;
// Find the start of the actual tree values (after the third '[')
char* start = strchr(inputLine, '[');
if (start) start = strchr(start + 1, '[');
if (start) start = strchr(start + 1, '[');
if (start) {
char* treePart = strdup(start);
char* endOfArray = strchr(treePart, ']');
if (endOfArray) *endOfArray = '\0';
char* nodeToken = strtok(treePart, ", ");
while (nodeToken) {
cleanToken(nodeToken);
if (strlen(nodeToken) > 0) {
treeNodes[nodeCount++] = strdup(nodeToken);
}
nodeToken = strtok(NULL, ", ");
}
free(treePart);
}
// 3. Execution
BSTIterator* it = NULL;
printf("[");
for (int i = 0; i < cmdCount; i++) {
if (i > 0) printf(", ");
if (strcmp(commands[i], "BSTIterator") == 0) {
TreeNode* root = buildTree(treeNodes, nodeCount);
it = createIterator(root);
printf("null");
} else if (strcmp(commands[i], "hasNext") == 0) {
printf("%s", (it && it->index + 1 < it->size) ? "true" : "false");
} else if (strcmp(commands[i], "next") == 0) {
printf("%d", it->values[++it->index]);
} else if (strcmp(commands[i], "hasPrev") == 0) {
printf("%s", (it && it->index > 0) ? "true" : "false");
} else if (strcmp(commands[i], "prev") == 0) {
if (it->index > 0) printf("%d", it->values[--it->index]);
else { it->index--; printf("null"); }
}
}
printf("]\n");
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n)
Initial in-order traversal visits all n nodes once
n
2n
✓ Linear Growth
Space Complexity
O(n)
Array stores all n node values
n
2n
✓ Linear Space
32.4K Views
MediumFrequency
~25 minAvg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.