LeetCode interview questions 32 -. III III [wins the printed upside down binary Offer Medium] [] [] [Python binary] [BFS]
problem
Implement a binary tree in accordance with the print function zigzag order, i.e. the first row from left to right order of printing, the second layer is printed in the order from right to left, then the third row from left to right order of printing, other line and so on.
For example:
Given a binary tree: [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
Return to its level through the results:
[
[3],
[20,9],
[15,7]
]
prompt:
节点总数 <= 1000
Thinking
BFS
当队列不为空:
当前层打印循环:
队首元素出队,记为 node
根据 flag 将 node.val 添加到 temp 尾部/头部
若左(右)子节点不为空,则将左(右)子节点加入队列
把当前 temp 中的所有元素加入 res
Time complexity: O (n-), n-number of nodes of the binary tree.
Space complexity: O (n-), n-number of nodes of the binary tree.
Python3 Code
# 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]]:
import collections
if not root:
return []
res, q = [], collections.deque()
# 做奇偶判断
flag = False
q.append(root)
while q:
# 输出是二维数组
temp = []
flag = not flag
for x in range(len(q)):
node = q.popleft()
# 尾插
if flag:
temp.append(node.val)
# 头插
else:
temp.insert(0, node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(temp)
return res