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

按之字形顺序打印二叉树

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

class Solution:
    def Print(self , pRoot: TreeNode) -> List[List[int]]:
        # write code here
        a=0
        b=0
        flag=0
        list_temp1=[]#存值
        list_temp2=[]#存结点
        List=[]

        now=pRoot
        while now!=None:
            list_temp1.append(now.val)
                                    
            if now.left!=None:
                list_temp2.append(now.left) 
                b+=1 

            if now.right!=None:
                list_temp2.append(now.right) 
                b+=1

            if a==0:
                if flag==0:
                    List.append(list_temp1[:])
                    flag=1
                else:
                    list_temp1.reverse()
                    List.append(list_temp1[:])
                    flag=0
                list_temp1.clear()
                a=b
                b=0

            if list_temp2:
                now=list_temp2.pop(0)
                a-=1
            else:
                break

        return List

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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