给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。例如:给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
该题同样是二叉树的层序遍历,不同于102 - 二叉树的层序遍历 - python之处在于,该题在输出遍历结果时需要考虑该层是奇数层还是偶数层:
- 如果是奇数层,则从左往右输出
- 如果是偶数层,则从右往左输出
AC code
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if root== None: return []
queue = [root]
res = []
index= 0
while queue:
cur = []
nextLayer = []
for node in queue:
cur.append(node.val)
if node.left:
nextLayer.append(node.left)
if node.right:
nextLayer.append(node.right)
# 判断是奇数层还是偶数层
res.append(cur) if index % 2 == 0 else res.append(cur[::-1])
index += 1
queue = nextLayer
return res