牛客网-直通BAt算法精讲课 Python按层次打印二叉树练习题

有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。

给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500

# -*- coding:utf-8 -*-

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class TreePrinter:
    def printTree(self, root):
        # write code here
        values=[]
        value=[]
        if root == None :
            return values
        last = root
        nlast = root
        q = []
        q.append(root)
        if root.left != None :
            q.append(root.left)
            nlast=root.left
        if root.right != None:
            q.append(root.right)
            nlast=root.right
        now=q.pop(0)
        value.append(now.val)
        values.append(value)
        value=[]
        if now == last:
            last=nlast
        while len(q):
            now=q.pop(0)
            value.append(now.val)
            if(now.left != None):
                q.append(now.left)
                nlast=now.left
            if(now.right != None):
                q.append(now.right)
                nlast=now.right
            if(now == last):
                last=nlast
                values.append(value[:])
                value=[]
        return values

总结:

1.把None 打成 null

2.没有注意好边界条件 root == None的情况

猜你喜欢

转载自blog.csdn.net/qq_40229367/article/details/88675136
今日推荐