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




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


class Solution(object):
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        level_queue = []
        ans = []
        level_queue.append(root)
        while level_queue:
            num = len(level_queue)
            temp = []
            while num > 0:
                cur = level_queue.pop(0)
                temp.append(cur.val)
                if cur.left:
                    level_queue.append(cur.left)
                if cur.right:
                    level_queue.append(cur.right)
                num -= 1
            ans.append(temp)
        for i in range(ans):
            if i % 2 != 0:
                ans[i] = ans[i][::-1]
        return ans

posted @ 2020-08-30 16:24  人间烟火地三鲜  阅读(141)  评论(0编辑  收藏  举报