Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 103 · BFS / Level Order

Binary Tree Zigzag Level Order Traversal

LeetCode 103 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

BFS + flip direction per level.

మధ్యస్థంTreeBreadth-First SearchBinary Tree
LeetCode లో తెరవండి ↗

నేను Binary Tree Zigzag Level Order Traversal (LeetCode 103) ను ఇలా పరిష్కరించాను — BFS / Level Order ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Normal level-order BFS, but alternate direction each level: on left-to-right levels append values, on right-to-left levels insert them at the front.

Approach

  1. 1

    BFS with a level marker.

  2. 2

    Flip leftToRight at every marker.

  3. 3

    Append or prepend the value depending on direction.

నేను ఎలా పరిష్కరించాను

BFS with direction flagPythonO(n) time
class Solution:
    def zigzagLevelOrder(self, root):
        if root is None:
            return []
        res = [[]]
        queue = [root, "\n"]
        leftToRight = True
        while len(queue) > 1:
            node = queue.pop(0)
            if node is None:
                continue
            if node == "\n":
                queue.append("\n")
                res.append([])
                leftToRight = not leftToRight
                continue
            else:
                if leftToRight:
                    res[-1].append(node.val)
                else:
                    res[-1].insert(0, node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return res
స్టెప్-త్రూ లోడ్ అవుతోంది…

Binary Tree Zigzag Level Order Traversal — తరచూ అడిగే ప్రశ్నలు

Binary Tree Zigzag Level Order Traversal వెనుక ఉన్న intuition ఏమిటి?

Normal level-order BFS, but alternate direction each level: on left-to-right levels append values, on right-to-left levels insert them at the front.

Binary Tree Zigzag Level Order Traversal (LeetCode 103) ను ఎలా పరిష్కరించాలి?

1. BFS with a level marker. 2. Flip leftToRight at every marker. 3. Append or prepend the value depending on direction.

Binary Tree Zigzag Level Order Traversal యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(n). (Accepted approach: BFS with direction flag.)

Binary Tree Zigzag Level Order Traversal లో సాధారణ పొరపాట్లు ఏమిటి?

unshift / insert(0) is O(k); a deque per level avoids it.