Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 173 · Iterator (Stack-based)

Binary Search Tree Iterator

LeetCode 173 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Controlled in-order traversal with a stack of left spines.

मध्यमStackTreeDesignBinary Search TreeBinary Tree

मी Binary Search Tree Iterator (LeetCode 173) असा सोडवला — Iterator (Stack-based) पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

An in-order traversal, paused. Keep a stack with the path of left children; the top is always the next smallest. After returning a node, push the left spine of its right subtree.

Approach

  1. 1

    Constructor: push root and all its left descendants.

  2. 2

    next: pop a node, push the left spine of node.right, return node.val.

  3. 3

    hasNext: stack is not empty.

मी कसा सोडवला

Stack of left spinesPythonO(1) amortised · O(h) space
class BSTIterator:
    def __init__(self, root):
        self.stack = []
        self.pushAll(root)  # always push extreme left items first

    def next(self):
        if len(self.stack) != 0:
            node = self.stack.pop()
            if node is not None:
                self.pushAll(node.right)  # go right and push all left nodes
            return node.val

    def hasNext(self):
        return len(self.stack) != 0

    def pushAll(self, node):
        cur = node
        while cur is not None:
            self.stack.append(cur)
            cur = cur.left
स्टेप-थ्रू लोड होत आहे…

Binary Search Tree Iterator — वारंवार विचारले जाणारे प्रश्न

Binary Search Tree Iterator मागील intuition काय आहे?

An in-order traversal, paused. Keep a stack with the path of left children; the top is always the next smallest. After returning a node, push the left spine of its right subtree.

Binary Search Tree Iterator (LeetCode 173) कसा सोडवावा?

1. Constructor: push root and all its left descendants. 2. next: pop a node, push the left spine of node.right, return node.val. 3. hasNext: stack is not empty.

Binary Search Tree Iterator ची time आणि space complexity किती आहे?

Time: O(1) amortised next. Space: O(h). (Accepted approach: Stack of left spines.)

Binary Search Tree Iterator मध्ये सामान्य चुका कोणत्या?

Flattening the whole tree up front uses O(n) memory instead of O(h).