《剑指Offer(第二版)》面试题32 - III. 从上到下打印二叉树 III

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

例如:
给定二叉树: [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果:
[
  [3],
  [20,9],
  [15,7]
]
 
提示:
节点总数 <= 1000
先正常层次遍历,再按层数反转

# 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 []

        q = []
        temp = []
        q.append(root)
        level = 1
        index = 0
        result = [[root.val]]

        while q[index:]:
            if q[index].left:
                temp.append(q[index].left)
            if q[index].right:
                temp.append(q[index].right)
            if index == len(q)-1:
                result.append([i.val for i in temp])
                for i in temp:
                    q.append(i)
                temp = []
                level += 1
            index += 1

        for i in range(1, len(result), 2):
            result[i] = result[i][::-1]
        return result[:-1]

 

你可能感兴趣的:(LeetCode点滴)