请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
结果集双端队列,避免翻转
# 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]]:
ans = []
if not root:
return ans
queue = collections.deque()
queue.append(root)
flag = False
while queue:
length = len(queue)
# 结果集也用双端队列,省去一次翻转动作
result = collections.deque()
for i in range(length):
p = queue.popleft()
if flag:
result.appendleft(p.val)
else:
result.append(p.val)
if p.left:
queue.append(p.left)
if p.right:
queue.append(p.right)
ans.append(list(result))
flag = not flag
return ans
双端队列 奇偶层逻辑分离
可以实际画一个双端队列感受一下
# 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]]:
ans = []
if not root:
return ans
queue = collections.deque()
queue.append(root)
while queue:
# 处理奇数层 从左向右打印 从左向右添加下层节点
length = len(queue)
result = list()
for i in range(length):
p = queue.popleft()
result.append(p.val)
if p.left:
queue.append(p.left)
if p.right:
queue.append(p.right)
ans.append(list(result))
if not queue:
break
# 处理偶数层 从右向左打印 从右向左添加下层节点
length = len(queue)
result = list()
for i in range(length):
p = queue.pop()
result.append(p.val)
if p.right:
queue.appendleft(p.right)
if p.left:
queue.appendleft(p.left)
ans.append(list(result))
return ans