[leetcode] 103. Binary Tree Zigzag Level Order Traversal @ python

原题

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 between).

For example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]

解法

使用BFS按层显示数值, 然后将奇数层的list反转
Time: O(v), v是二叉树节点的数量
Space: O(1)

# 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 = self.bfs(root)
        res = [res[i] if i%2 == 0 else res[i][::-1] for i in range(len(res))]
        return res
        
    def bfs(self, root):
        res = []
        if not root:
            return res
        q = [root]
        while q:
            res.append([node.val for node in q])
            q = [kid for node in q for kid in (node.left, node.right) if kid]
            
        return res

你可能感兴趣的:(Leetcode)