Leetcode 103. 二叉树的锯齿形层次遍历(Python3)

103. 二叉树的锯齿形层次遍历

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回锯齿形层次遍历如下:

[
  [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: TreeNode) -> List[List[int]]:
        #BFS
        if not root:
            return []
        res = []
        que = [root]
        flag = -1
        while que:
            flag = -flag
            val = []
            q = []
            for i in que:
                val.append(i.val)
                if i.left:
                    q.append(i.left)
                if i.right:
                    q.append(i.right)
            res.append(val[::flag])
            que = q
        return res             

 

你可能感兴趣的:(python3,leetcode)