这道题只需在102的基础上稍微变化下就行,很简单了,fighting
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# 最终结果
res = []
# 存放每一层结果
levelRes = []
if root == None:
return res
# 当前一层的节点
current = []
# 下一层的节点
next = []
# 根节点加入
current.append(root)
# 标记是正向还是反向来
flag = True
while len(current) > 0:
node = current.pop()
if flag:
# (正向,则先添加左节点,再添加右节点)
if node.left != None:
next.append(node.left)
if node.right != None:
next.append(node.right)
else :
# (反向。先添加右节点,再添加左节点)
if node.right != None:
next.append(node.right)
if node.left != None:
next.append(node.left)
# 加入访问节点的值
levelRes.append(node.val)
if len(current) == 0:
current = next
next = []
res.append(levelRes)
levelRes = []
# 将flag取反
flag = not flag
return res