Binary Tree Zigzag Level Order Traversal
LeetCode 103 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
BFS + flip direction per level.
मैंने Binary Tree Zigzag Level Order Traversal (LeetCode 103) ऐसे हल किया — BFS / Level Order पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Normal level-order BFS, but alternate direction each level: on left-to-right levels append values, on right-to-left levels insert them at the front.
Approach
- 1
BFS with a level marker.
- 2
Flip leftToRight at every marker.
- 3
Append or prepend the value depending on direction.
मैंने कैसे हल किया
BFS with direction flagPythonO(n) time
class Solution:
def zigzagLevelOrder(self, root):
if root is None:
return []
res = [[]]
queue = [root, "\n"]
leftToRight = True
while len(queue) > 1:
node = queue.pop(0)
if node is None:
continue
if node == "\n":
queue.append("\n")
res.append([])
leftToRight = not leftToRight
continue
else:
if leftToRight:
res[-1].append(node.val)
else:
res[-1].insert(0, node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return resBinary Tree Zigzag Level Order Traversal — अक्सर पूछे जाने वाले प्रश्न
Binary Tree Zigzag Level Order Traversal के पीछे intuition क्या है?
Normal level-order BFS, but alternate direction each level: on left-to-right levels append values, on right-to-left levels insert them at the front.
Binary Tree Zigzag Level Order Traversal (LeetCode 103) कैसे हल करें?
1. BFS with a level marker. 2. Flip leftToRight at every marker. 3. Append or prepend the value depending on direction.
Binary Tree Zigzag Level Order Traversal की time और space complexity क्या है?
Time: O(n)। Space: O(n)। (Accepted approach: BFS with direction flag।)
Binary Tree Zigzag Level Order Traversal में आम गलतियाँ क्या हैं?
unshift / insert(0) is O(k); a deque per level avoids it.