Binary Tree Level Order Traversal
LeetCode 102 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
BFS with a level marker.
मैंने Binary Tree Level Order Traversal (LeetCode 102) ऐसे हल किया — BFS / Level Order पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Breadth-first search with a queue visits nodes level by level. A marker ('\n') in the queue tells you where one level ends and the next begins.
Approach
- 1
Queue starts with root and a marker.
- 2
Pop: marker → re-append it and start a new level list.
- 3
Node → add its value and enqueue its children.
- 4
Stop when only the marker is left.
मैंने कैसे हल किया
BFS with markerPythonO(n) time · O(n) space
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root is None:
return []
queue=deque([root,"\n"])
res=[[]]
while len(queue)>1:
node= queue.popleft()
if node is None:
continue
if node is "\n":
queue.append(node)
res.append([])
continue
res[-1].append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return resBinary Tree Level Order Traversal — अक्सर पूछे जाने वाले प्रश्न
Binary Tree Level Order Traversal के पीछे intuition क्या है?
Breadth-first search with a queue visits nodes level by level. A marker ('\n') in the queue tells you where one level ends and the next begins.
Binary Tree Level Order Traversal (LeetCode 102) कैसे हल करें?
1. Queue starts with root and a marker. 2. Pop: marker → re-append it and start a new level list. 3. Node → add its value and enqueue its children. 4. Stop when only the marker is left.
Binary Tree Level Order Traversal की time और space complexity क्या है?
Time: O(n)। Space: O(n)। (Accepted approach: BFS with marker।)
Binary Tree Level Order Traversal में आम गलतियाँ क्या हैं?
`node is "\n"` relies on string interning; == is the safe comparison.