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).