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
LeetCode-এ খুলুন ↗

আমি 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).