LeetCode Solutions

173. Binary Search Tree Iterator

Time: Constructor: $O(n)$, next(): $O(1)$, hasNext(): $O(1)$

Space: $O(n)$

			

class BSTIterator {
 public:
  BSTIterator(TreeNode* root) {
    inorder(root);
  }

  /** @return the next smallest number */
  int next() {
    return vals[i++];
  }

  /** @return whether we have a next smallest number */
  bool hasNext() {
    return i < vals.size();
  }

 private:
  int i = 0;
  vector<int> vals;

  void inorder(TreeNode* root) {
    if (root == nullptr)
      return;

    inorder(root->left);
    vals.push_back(root->val);
    inorder(root->right);
  }
};
			

class BSTIterator {
  public BSTIterator(TreeNode root) {
    inorder(root);
  }

  /** @return the next smallest number */
  public int next() {
    return vals.get(i++);
  }

  /** @return whether we have a next smallest number */
  public boolean hasNext() {
    return i < vals.size();
  }

  private int i = 0;
  private List<Integer> vals = new ArrayList<>();

  private void inorder(TreeNode root) {
    if (root == null)
      return;

    inorder(root.left);
    vals.add(root.val);
    inorder(root.right);
  }
}
			

class BSTIterator:
  def __init__(self, root: Optional[TreeNode]):
    self.stack = []
    self.pushLeftsUntilNone(root)

  def next(self) -> int:
    root = self.stack.pop()
    self.pushLeftsUntilNone(root.right)
    return root.val

  def hasNext(self) -> bool:
    return self.stack

  def pushLeftsUntilNone(self, root: Optional[TreeNode]):
    while root:
      self.stack.append(root)
      root = root.left