二叉树的层次遍历代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: # root为空时直接返回[]
return []
res = [] # 返回的最终结果
cur_nodes = [root] # 当前访问层
next_nodes = [] # 下一层需要访问的
res.append([i.val for i in cur_nodes]) # 先把第一层的值放入res中
while cur_nodes or next_nodes: # 当前结点或下一层结点不为空
for node in cur_nodes: # 当前结点的所有孩子都加入next_nodes
if node.left:
next_nodes.append(node.left)
if node.right:
next_nodes.append(node.right)
# 下一层结点不为空时加入res
if next_nodes:
res.append(
[i.val for i in next_nodes]
)
cur_nodes = next_nodes # 更新当前结点为next_nodes
next_nodes = [] # 下一层结点置空
return res
我的思路:
设置一个flag
对奇数层采取和普通层次遍历相同的顺序
对偶数层采取和普通层次遍历相反的顺序
res不变 ans用来存放满足题目要求的输出
我的代码:
def zigzagLevelOrder(self, root):
# root为空时直接返回[]
if not root:
return []
flag=1
res = []
ans=[]
cur_nodes = [root] # 当前访问层
next_nodes = [] # 下一层需要访问的
res.append([i.val for i in cur_nodes]) # 先把第一层的值放入res和ans中
ans.append([i.val for i in cur_nodes])
while cur_nodes or next_nodes: # 当前结点或下一层结点不为空
for node in cur_nodes: # 当前结点的所有孩子都加入next_nodes
if node.left:
next_nodes.append(node.left)
if node.right:
next_nodes.append(node.right)
if next_nodes: # 下一层结点不为空时加入res
res.append(
[i.val for i in next_nodes]
)
# 判断是奇数层还是偶数层
if flag%2==1:
tmp=next_nodes[::-1]
else:
tmp=next_nodes
flag+=1
# 将节点加入ans
if tmp:
ans.append(
[i.val for i in tmp]
)
cur_nodes = next_nodes # 更新当前结点为next_nodes
next_nodes = [] # 下一层结点置空
return ans