# 173. Binary Search Tree Iterator

## 1.問題

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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKP_al430aDt4QwZfzF%2F-LKPbPjDdgqB8l2Zk4cz%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-21%20%E4%B8%8A%E5%8D%8811.53.03.png?alt=media\&token=777394ad-274b-410a-bf3e-314aef9fb152)

## 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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKP_al430aDt4QwZfzF%2F-LKPbX24bOiUIu8xu3mx%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-21%20%E4%B8%8A%E5%8D%8811.53.39.png?alt=media\&token=f4bf4b12-8aed-416b-9b5f-8c3f0b5e54b1)
