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