请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],3
/ \
9 20
/ \
15 7
返回其层次遍历结果:[
[3],
[20,9],
[15,7]
]
思路
这道题只是将上一道题改成了“S”型遍历,其他都不变,因此只需要在上一道的基础上进行改进即可。
不用分层的最原始的BFS代码为:
# 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 = []
queue.append(root)
while queue:
node = queue[0]
queue = queue[1:]
res.append(node.val)
if queue.left:
queue.append(queue.left)
if queue.right:
queue.append(queue.right)
return res
上一道题分层输出的代码如下:
# 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 = []
queue.append(root)
while queue:
temRes = []
for i in range(len(queue)):
node = queue[0]
queue = queue[1:]
temRes.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(temRes)
return res
对于这道题,只需要对分层输出的偶数层进行reverse操作即可,即:
for i,v in enumerate(res):
if i % 2 ==1:
print(res[i])
res[i] = res[i][::-1]
最终代码为:
# 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 = []
queue.append(root)
while queue:
temRes = []
for i in range(len(queue)):
node = queue[0]
queue = queue[1:]
temRes.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(temRes)
for i,v in enumerate(res):
if i % 2 ==1:
print(res[i])
res[i] = res[i][::-1]
return res