> For the complete documentation index, see [llms.txt](https://cai-sen-se.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cai-sen-se.gitbook.io/leetcode/1-200/173.-er-cha-sou-suo-shu-dai-qi.md).

# 173. 二叉搜索树迭代器

<https://leetcode-cn.com/problems/binary-search-tree-iterator/>

## 解法一：

递归中序遍历存到数组中，依次访问即可。

## 解法二：

按 94.二叉树的中序遍历 解法二的非递归方法，进行相应改造

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

class BSTIterator:

    def __init__(self, root: TreeNode):
        p = root
        self.stack = []  #全局栈
        #初始先走到最左子，路径依次入栈
        while p:
            self.stack.append(p)
            p = p.left

    def next(self) -> int:
        p = self.stack.pop()  #出栈。不用考虑栈空，题目假设不为空
        res = p  #访问的结点
        #如有右子，按如上方法处理
        if p.right:
            p = p.right
            while p:
                self.stack.append(p)
                p = p.left
        return res.val
        
    def hasNext(self) -> bool:
        #查看栈是否为空即可
        return True if len(self.stack) > 0 else False
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cai-sen-se.gitbook.io/leetcode/1-200/173.-er-cha-sou-suo-shu-dai-qi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
