Leetcode 103. Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate bet
ween).

For example:
Given binary tree [3,9,20,null,null,15,7],
Leetcode 103. Binary Tree Zigzag Level Order Traversal_第1张图片
return its zigzag level order traversal as:
[[3],[20,9],[15,7]]

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        res = []
        if not root:
            return res
        
        queue = [root]
        
        while queue:
            level = []
            for _ in range(len(queue)):
                curr = queue.pop(0)
                level.append(curr.val)
                if curr.left:
                    queue.append(curr.left)
                if curr.right:
                    queue.append(curr.right)
            if len(res) % 2 == 1:
                level = level[::-1]
            res.append(level)
        
        return res

你可能感兴趣的:(leetcode,python,tree,bfs,leetcode,python)