# Binary Search Tree Iterator 07/28

Design an iterator over a binary search tree with the following rules:

* Elements are visited in ascending order (i.e. an in-order traversal)
* `next()` and `hasNext()` queries run in O(*1*) time in **average**.

Have you met this question in a real interview?  Yes

#### Example

For the following binary search tree, in-order traversal by using iterator is `[1, 6, 10, 11, 12]`

```
   10
 /    \
1      11
 \       \
  6       12
```

#### Challenge

Extra memory usage O(h), h is the height of the tree.

**Super Star**: Extra memory usage O(1)空间和时间复杂度 不满足条件

```java
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 * Example of iterate a tree:
 * BSTIterator iterator = new BSTIterator(root);
 * while (iterator.hasNext()) {
 *    TreeNode node = iterator.next();
 *    do something for node
 * } 
 */


public class BSTIterator {
    /*
    * @param root: The root of binary tree.
    */
    private Stack<TreeNode> stack;
    public BSTIterator(TreeNode root) {
        // do intialization if necessary
        this.stack = new Stack<>();
        
        while(root!= null){
            stack.push(root);
            root = root.left;
        }
        
    }

    /*
     * @return: True if there has next node, or false
     */
    public boolean hasNext() {
        // write your code here
        return !stack.isEmpty();
    }

    /*
     * @return: return next node
     */
    public TreeNode next() {
        // write your code here
        
        TreeNode node = stack.pop();
        if(node.right != null){
            TreeNode right = node.right;
            while(right!=null){
                stack.push(right);
                right = right.left;
            }
        }
       
        return node;
    }
}
```

Morris Traversal 非递归，不用stack，O(1 )空间复杂度


---

# Agent Instructions: 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://shuati.gitbook.io/crack-lintcode/binary-tree/binary-search-tree-iterator-07-28.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.
