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