> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/173.-binary-search-tree-iterator.md).

# 173. Binary Search Tree Iterator

## 1.問題

* 實作BST的迭代器, constructor, next, hasNext

![](/files/-LKPbPjDdgqB8l2Zk4cz)

## 2.想法

* 用stack儲存BST的left主線上的node
  * last in first out的特性
* BST的left主線是最小值, 而left主線上node的每一個right node的left主線又是另一個list, 其大小介於該node的以及node的上一次中
  * 因此每次pop stack的元素時, 要再將top的right以及其left主線上的元素全部加入

## 3.程式碼

```
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    BSTIterator(TreeNode *root) {
        TreeNode * curr = root;
        while (curr) {
            st.push(curr);
            curr = curr->left;
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !st.empty();
    }

    /** @return the next smallest number */
    int next() {
        int val = st.top()->val;
        TreeNode* node = st.top()->right;
        st.pop();
        while (node) {
            st.push(node);
            node = node->left;
        }
        return val;
    }
private:
    stack<TreeNode*> st;
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */
```

## 4.Performance

![](/files/-LKPbX24bOiUIu8xu3mx)


---

# 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, and the optional `goal` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/173.-binary-search-tree-iterator.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
