> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Binary Search Tree Iterator Python Solution

> Tested Python solution for LeetCode 173 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 173, [Medium](/catalog/medium). Topics: [Stack](/catalog/topics/stack), [Tree](/catalog/topics/tree), [Design](/catalog/topics/design), [Binary Search Tree](/catalog/topics/binary-search-tree), [Binary Tree](/catalog/topics/binary-tree), Iterator. [View on LeetCode](https://leetcode.com/problems/binary-search-tree-iterator/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 173   # by problem number
lcpy gen -s binary_search_tree_iterator   # by problem name
```

## Problem

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.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2018/12/25/bst-tree.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, 10\<sup>5\</sup>]
* 0 \<= Node.val \<= 10\<sup>6\</sup>
* At most 10\<sup>5\</sup> 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?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/binary_search_tree_iterator/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/binary_search_tree_iterator/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class BSTIterator:
    # Time: O(1) average per operation
    # Space: O(h)
    def __init__(self, root: TreeNode[int] | None) -> None:
        self._stack: list[TreeNode[int]] = []
        self._push_left(root)

    def _push_left(self, node: TreeNode[int] | None) -> None:
        while node is not None:
            self._stack.append(node)
            node = node.left

    # Time: O(1) average
    # Space: O(1)
    def next(self) -> int:
        node = self._stack.pop()
        self._push_left(node.right)
        return node.val

    # Time: O(1)
    # Space: O(1)
    def has_next(self) -> bool:
        return len(self._stack) > 0
```

## Complexity

| Time | Space |
| - | - |
| O(1) average per operation | O(h) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.