---
# System prepended metadata

title: Leetcode 173. Binary Search Tree Iterator
tags: [Leetcode]

---

[link](https://leetcode.com/problems/binary-search-tree-iterator/)

---

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.
Notice that 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() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.


#### Example 1:

![](https://hackmd.io/_uploads/By2tdQ1sh.png)

```
Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]

Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next();    // return 3
bSTIterator.next();    // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 20
bSTIterator.hasNext(); // return 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, and next.
 

Follow up:

Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?

---

The BSTIterator class implements an iterator for a binary search tree (BST) that allows you to iterate over the nodes in ascending order.

The constructor (__init__) initializes the iterator. It takes the root node of the BST as input and initializes the stack. The stack is used to simulate an in-order traversal of the BST, ensuring that the elements are iterated in ascending order.

In the constructor, the code performs an initial in-order traversal of the BST starting from the root node. It pushes all the left children (in non-decreasing order) onto the stack. This ensures that the first element returned by the iterator will be the leftmost (smallest) element of the BST.

The next method returns the next smallest element in the BST. It pops an element from the stack and returns its value. If the popped node has a right child, it performs another in-order traversal starting from the right child to push all the left children of that subtree onto the stack. This guarantees that the next call to next will return the next smallest element in the BST.

The hasNext method checks if the iterator has more elements to iterate over. It returns True if the stack is not empty, indicating that there are more elements to process. Otherwise, it returns False.

#### Solution 1
```python=
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class BSTIterator:

    def __init__(self, root: Optional[TreeNode]):
        self.stack = []
        while root:
            self.stack.append(root)
            root = root.left
        

    def next(self) -> int:
        res = self.stack.pop()
        cur = res.right
        while cur:
            self.stack.append(cur)
            cur = cur.left
        return res.val
        

    def hasNext(self) -> bool:
        return False if self.stack == [] else True
        
```
The time complexity of both next and hasNext methods is O(1) on average since each node in the BST is processed exactly once. 

The space complexity is O(h), where h is the height of the BST, due to the stack used to store nodes during traversal. In the worst case, the space complexity can be O(n) if the BST is highly unbalanced, but in a balanced BST, it will be O(log n).