题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

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

全部评论

相关推荐

流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务