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.