MediumNo. 0173

Binary Search Tree Iterator — LeetCode 173 Python Solution

Pattern
Stack
Topics
Stack, Tree, Design, Binary Search Tree, Binary Tree, Iterator
On a study list
Top Interview 150
Reading time
6 min

The problem

Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor.

Example

Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]
Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);

Python solution

PythonSolution
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class BSTIterator:
    def __init__(self, root: TreeNode):
        def inorder(root):
            if root:
                inorder(root.left)
                self.vals.append(root.val)
                inorder(root.right)

        self.cur = 0
        self.vals = []
        inorder(root)

    def next(self) -> int:
        res = self.vals[self.cur]
        self.cur += 1
        return res

    def hasNext(self) -> bool:
        return self.cur < len(self.vals)


# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 173. Binary Search Tree Iterator is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 173. Binary Search Tree Iterator?

LeetCode 173. Binary Search Tree Iterator is rated Medium on LeetCode.

What is the time complexity of LeetCode 173. Binary Search Tree Iterator?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 173. Binary Search Tree Iterator?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 173. Binary Search Tree Iterator cover?

LeetCode 173. Binary Search Tree Iterator is tagged Stack, Tree, Design, Binary Search Tree, Binary Tree and Iterator on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.