Leetcode 剑指 Offer 32 - III.从上到下打印二叉树 III

Leetcode 剑指 Offer 32 - III.从上到下打印二叉树 III

1 题目描述(Leetcode题目链接)

  请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推

    3
   / \
  9  20
    /  \
   15   7
[
  [3],
  [20,9],
  [15,7]
]

提示:节点总数 <= 1000

2 题解

  层序遍历

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

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        res = []
        queue = collections.deque([root])
        tag = 0
        while queue:
            cur = []
            num = len(queue)
            while num:
                num -= 1
                node = queue.popleft()
                cur.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            if tag: 
                cur = cur[::-1]
            tag ^= 1
            res.append(cur)
        return res


你可能感兴趣的:(Leetcode)