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.