← Home

173. Binary Search Tree Iterator

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
173

This is one of those problems where the clean idea matters more than the amount of code. For 173. Binary Search Tree Iterator, the solution in this repository is mainly a two pointers solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, stack, sliding window.

The notes already sitting in the source point us in the right direction:

  • naive
  • Approach 1: Flattening the BST
  • time: O(N), space: O(N)

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are inorder, next, hasNext, push_left.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//naive
02//Approach 1: Flattening the BST
03//Runtime: 60 ms, faster than 95.83% of C++ online submissions for Binary Search Tree Iterator.
04//Memory Usage: 29.2 MB, less than 10.86% of C++ online submissions for Binary Search Tree Iterator.
05//time: O(N), space: O(N)
06/**
07 * Definition for a binary tree node.
08 * struct TreeNode {
09 *     int val;
10 *     TreeNode *left;
11 *     TreeNode *right;
12 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
13 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
14 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
15 * };
16 */
17class BSTIterator {
18public:
19    vector<int> values;
20    int pos;
21    
22    void inorder(TreeNode* node){
23        if(!node) return;
24        inorder(node->left);
25        values.push_back(node->val);
26        inorder(node->right);
27    }
28    
29    BSTIterator(TreeNode* root) {
30        inorder(root);
31        pos = 0;
32    }
33    
34    /** @return the next smallest number */
35    int next() {
36        return values[pos++];
37    }
38    
39    /** @return whether we have a next smallest number */
40    bool hasNext() {
41        return pos < values.size();
42    }
43};
44
45/**
46 * Your BSTIterator object will be instantiated and called as such:
47 * BSTIterator* obj = new BSTIterator(root);
48 * int param_1 = obj->next();
49 * bool param_2 = obj->hasNext();
50 */
51
52//binary tree inorder traversal using stack
53//https://github.com/keineahnung2345/leetcode-cpp-practices/blob/master/94.%20Binary%20Tree%20Inorder%20Traversal.cpp#L126
54//Runtime: 56 ms, faster than 98.62% of C++ online submissions for Binary Search Tree Iterator.
55//Memory Usage: 27.8 MB, less than 10.86% of C++ online submissions for Binary Search Tree Iterator.
56class BSTIterator {
57public:
58    stack<TreeNode*> stk;
59    TreeNode* cur;
60    
61    BSTIterator(TreeNode* root) {
62        cur = root;
63    }
64    
65    /** @return the next smallest number */
66    int next() {
67        while(cur){
68            stk.push(cur);
69            cur = cur->left;
70        }
71        cur = stk.top(); stk.pop();
72        int val = cur->val;
73        cur = cur->right;
74        return val;
75    }
76    
77    /** @return whether we have a next smallest number */
78    bool hasNext() {
79        return cur || !stk.empty();
80    }
81};
82 
83//official
84//Approach 2: Controlled Recursion
85//Runtime: 68 ms, faster than 83.26% of C++ online submissions for Binary Search Tree Iterator.
86//Memory Usage: 28 MB, less than 10.86% of C++ online submissions for Binary Search Tree Iterator.
87//time for hasNext(): O(1)
88//time for next(): O(n) in worst case, amortized O(1)
89//space: O(h)
90class BSTIterator {
91public:
92    stack<TreeNode*> stk;
93    
94    void push_left(TreeNode* node){
95        while(node){
96            stk.push(node);
97            node = node->left;
98        }
99    }
100    
101    BSTIterator(TreeNode* root) {
102        //go left
103        push_left(root);
104    }
105    
106    /** @return the next smallest number */
107    int next() {
108        TreeNode* cur = stk.top(); stk.pop();
109        //visit itself
110        int val = cur->val;
111        //go right
112        if(cur->right){
113            push_left(cur->right);
114        }
115        return val;
116    }
117    
118    /** @return whether we have a next smallest number */
119    bool hasNext() {
120        return !stk.empty();
121    }
122};

Cost

Complexity

Time
O(N), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.