Skip to content

Latest commit

 

History

History
132 lines (100 loc) · 4.7 KB

File metadata and controls

132 lines (100 loc) · 4.7 KB

173. Binary Search Tree Iterator (Medium)

Date and Time: Jan 20, 2025, 22:25 (EST)

Link: https://leetcode.com/problems/binary-search-tree-iterator


Question:

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. The pointer should be initialized to a non-existent number smaller than any element in the BST.

  • boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.

  • int next() Moves the pointer to the right, then returns the number at the pointer.

Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.

You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.


Example 1:

Input:
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]

Output:
[null, 3, 7, true, 9, true, 15, true, 20, false]

Explanation:

BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next();    // return 3
bSTIterator.next();    // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 20
bSTIterator.hasNext(); // return False

Constraints:

  • The number of nodes in the tree is in the range [1, 10^5].

  • 0 <= Node.val <= 10^6

  • At most 10^5 calls will be made to hasNext, and next.


Walk-through:

Use stack[] to save every nodes, everytime we pop from stack[] will only get the smallest element from the end of stack.

next() function: we first get the current smallest by popping from stack[], then search its right subtree to find the deep-left node (smallest element), we are also appending nodes in this path.

hasNext(): we can just determine if stac[] is empty or not.

          7
       /    \
     3       15
    /  \    /  \
   1    6  9   20
       /
      5 

Python Solution:

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

    # In-order traversal: left->root->right
    # Reach the deep left (smallest) node, save all the nodes on path
    # TC: O(n), SC: O(h)
    def __init__(self, root: Optional[TreeNode]):
        self.stack = []
        while root:
            self.stack.append(root)
            root = root.left
    
    # Return current node from stack, point to the next smallest elem
    def next(self) -> int:
        node = self.stack.pop()
        curr = node.right
        while curr:
            self.stack.append(curr)
            curr = curr.left
        return node.val
        
    # Check if stack is empty
    def hasNext(self) -> bool:
        return len(self.stack) > 0

#          7
#       /    \
#     3       15
#    /  \    /  \
#   1    6  9   20
#       /
#      5 

# stack = []
# [1,3,5,6,7,9,15,20]


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

Time Complexity: $O(n)$
Space Complexity: $O(h)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms