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

按之字形顺序打印二叉树

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

class Solution:
    def Print(self , root: TreeNode) :
        if root==None:
            return []

        else:
            cur_nodes=[root]
            next_layers=[]
            cur_res=[]
            res=[]
            direction=False #False means 从右->左

            while len(cur_nodes)!=0:
                for node in cur_nodes:
                    if node == None:
                        pass
                    else:
                        if direction==False:
                            next_layers.insert(0,node.left)
                            next_layers.insert(0,node.right)

                        else:
                            next_layers.insert(0,node.right)
                            next_layers.insert(0,node.left)
                        cur_res.append(node.val)
                if cur_res:
                    res.append(cur_res)#把当前层的输出push进总输出
                    if direction:#改变方向
                        direction=False
                    else:
                        direction=True

                    cur_nodes=next_layers#开始遍历下一层
                    cur_res=[]#清空当前层的一些东西
                    next_layers = []
                else:
                    break

            return res

全部评论

相关推荐

11-03 14:38
重庆大学 Java
AAA求offer教程:我手都抬起来了又揣裤兜了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务