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

# 173. Binary Search Tree Iterator (stack)

![](/files/-Mji_8f7xpVBKYn97tnH)

![](/files/-Mji_B5f30dE1qQadRxK)

![](/files/-Mji_FG4kZ2B8LhPQzGQ)

time: O(n), n is node nums, to constuct iterator

space: O(n), use stack, there are n nodes number add to stack

next(): O(1), average, somtimes need add left nodes&#x20;

hasNext(): O(1),&#x20;

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 
 因為 inorder 都是有序的, 所以從最小開始（ leftmost
 一路 push 到 stack, 這樣取出時, 會從最小開始取出
 
 
   8  -> root
  /
 2  
/ \    
1  4   => [1, 2, 8]

from root, do leftmost to push into stack
stack
1  => pop1
2
8

2 => pop 2 => 4
8


4
8
 
 */
class BSTIterator {
    private Deque<TreeNode> stack;
    public BSTIterator(TreeNode root) {
        stack = new ArrayDeque<>();
        findMostLeft(root); // add left all first
    }
    private void findMostLeft(TreeNode node) { // add left all first
        while (node != null) {
            stack.push(node);
            node = node.left;
        }
    }
    
    public int next() {
        TreeNode node = stack.pop();
        if (node.right != null) { // if have right subtree
            findMostLeft(node.right); // add right node's left all first
        }
        return node.val;
    }
    
    public boolean hasNext() {
        return !stack.isEmpty();
    }
}

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator obj = new BSTIterator(root);
 * int param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */
```


---

# 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://timmybeeflin.gitbook.io/cracking-leetcode/tree/173.-binary-search-tree-iterator-stack.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.
