leetcode:二叉树的锯齿形层序遍历

leetcode:二叉树的锯齿形层序遍历
思路:
比正常遍历多了一个奇偶层判断

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if root is None:
            return []
        res = []
        q = [root]
        count = 1
        while len(q) > 0:
            q1 = []
            tempres = []
            for node in q:
                if node.left is not None:
                    q1.append(node.left)
                if node.right is not None:
                    q1.append(node.right)
                tempres.append(node.val)
            if count % 2 == 0:
                tempres.reverse()
            q = q1
            res.append(tempres)
            count += 1
        return res

总结:
list.reverse()

上一篇:Python3基础之核心数据类型空值对象None、整形int、浮点型float、字符串str、复数complex、布尔bool


下一篇:BigDecimal详解