题目
给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{1,2,3,#,#,4,5}
该二叉树之字形层序遍历的结果是
[
[1],
[3,2],
[4,5]
]
示例1
输入:{1,2,3,#,#,4,5}
返回值:[[1],[3,2],[4,5]]
说明:如题面解释,第一层是根节点,从左到右打印结果,第二层从右到左,第三层从左到右。
解题思路
在上一题BM26层序遍历的基础上,只需要让奇数层反转就可以了
题解
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return int整型二维数组
#
import queue
class Solution:
def Print(self , pRoot: TreeNode) -> List[List[int]]:
l=[]
q = queue.Queue()
level_num=1
next_num=0
count=1
# 1.先将根节点放入队列中
if pRoot!= None:q.put(pRoot)
new_l=[]
# 2.遍历该节点是否有孩子节点,如果有将该节点出队,并将孩子节点放入队列中
while q.empty()== False:
new_pRoot = q.get()
new_l.append(new_pRoot.val)
level_num-=1
# 如果该节点有左子树
if new_pRoot.left!=None:
q.put(new_pRoot.left)
next_num+=1
# 如果该节点有右子树
if new_pRoot.right!=None:
q.put(new_pRoot.right)
next_num+=1
# 当该层级遍历完成
if level_num==0:
#若为奇数层,则反转行
if count%2==0: new_l=new_l[::-1]
count+=1
l.append(new_l)
new_l=[]
level_num = next_num
next_num = 0
return l