思路:
比正常遍历多了一个奇偶层判断
代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
res = []
q = [root]
count = 1
while len(q) > 0:
q1 = []
tempres = []
for node in q:
if node.left is not None:
q1.append(node.left)
if node.right is not None:
q1.append(node.right)
tempres.append(node.val)
if count % 2 == 0:
tempres.reverse()
q = q1
res.append(tempres)
count += 1
return res
总结:
list.reverse()