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.