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

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pRoot TreeNode类 
# @return int整型二维数组
#
import queue as Q
class Solution:
    def Print(self , pRoot: TreeNode) -> List[List[int]]:
        # write code here
        res = []
        que = Q.Queue()
        if pRoot:
            que.put(pRoot)
        flag = 0
        while not que.empty():
            outrow = []
            length = que.qsize()
            for i in range(length):
                this = que.get()
                outrow.append(this.val)
                if this.left:
                    que.put(this.left)
                if this.right:
                    que.put(this.right)
            if flag == 0:
                res.append(outrow)
                flag = 1
            else:
                outrow.reverse()
                res.append(outrow)
                flag = 0

        return res

全部评论

相关推荐

10-06 12:46
门头沟学院 Java
跨考小白:定时任务启动
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务