Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 102 · BFS / Level Order

Binary Tree Level Order Traversal

LeetCode 102 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

BFS with a level marker.

நடுத்தரம்TreeBreadth-First SearchBinary Tree

நான் 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. 1

    Queue starts with root and a marker.

  2. 2

    Pop: marker → re-append it and start a new level list.

  3. 3

    Node → add its value and enqueue its children.

  4. 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 res
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

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