题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
from math import inf
#from math import inf
# 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]]:
res = []
if not pRoot:
return []
info = queue.Queue()
info.put(pRoot)
leftToRight = True
while not info.empty():
row = []
n = info.qsize()
for i in range(n):
tmp = info.get()
row.append(tmp.val)
if tmp.left:
info.put(tmp.left)
if tmp.right:
info.put(tmp.right)
if leftToRight:
res.append(row)
leftToRight = False
else:
res.append(row[::-1])
leftToRight = True
return res
查看8道真题和解析