Binary Search Tree Iterator
LeetCode 173 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Controlled in-order traversal with a stack of left spines.
मैंने 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
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.
मैंने कैसे हल किया
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.leftBinary 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).