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.