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

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0?tpId=295&tqId=23454&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param ppRoot TreeNode类
# @return int整型二维数组
#
class Solution:
    def Print(self, pRoot: TreeNode) -> list[list[int]]:
        # write code here

        # write code here
        """设置队列queue,并设置length设置每次队列新加的一层元素的长度
        ,当新加的元素全都出队以后,这时需要将结果统计一次放入到res2这个最终的结果中"""

        queue = []

        res2 = []
        if not pRoot:
            return None
        queue.append(pRoot)
        level=0
        while queue:
            res = []
            length = len(queue)
           
            """打个比方,比如刚开始添加了一个元素,入对,然后只需要Pop一次,就统计结果"""
            # 第二次,假如队列有2个元素,那么需要pop2次,再统计res中的结果
            while length > 0:
                pRoot = queue.pop(0)
                length -= 1

                if pRoot.left:
                    queue.append(pRoot.left)
                if pRoot.right:
                    queue.append(pRoot.right)

                if level%2==0:
                    res.append(pRoot.val)
                else:
				  #往当前列表的前面插入实现反向
                    res.insert(0,pRoot.val)
		#设置level变量通过层数改变打印的方向
            level+=1
            res2.append(res)
        return res2

全部评论

相关推荐

牛油果甜奶昔:别的先不说,牛客还能内推护士?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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