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.