NOWCODER 剑指offer ※从上到下打印二叉树

教训:

1、空序列的话返回[]而不是None

2、for i in list:  如果最后一个循环list改变值的话,并不会再循环下去

运行时间:31ms

占用内存:5720k

思路:每次保存上一层的所有结点,当左右子树都为空时,返回结果列表

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        if not root:
            return []
        temp = [root]
        res = [root.val]
        temp2 = []
        while (1):
            for i in temp:
                if(i.left):
                    res.append(i.left.val)
                    temp2.append(i.left)
                if (i.right):
                    res.append(i.right.val)
                    temp2.append(i.right)
                if (not i.left) and (not i.right):
                    return res
                if (i==temp[-1]):
                    temp = temp2
                    temp2 = []

————————————————————————————————————————————

最优解思路一样,不过我写的有些重复累赘

每个循环结果都扩充当前结点值,而temp数组保存下根节点的左右子树,结束条件是保存左右子树的数组为空

运行时间:30ms

占用内存:5612k

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        if not root:
            return []
        temp = [root]
        res = []
        while (temp):
            temp2 = []
            for i in temp:
                res.append(i.val)
                if(i.left):temp2.append(i.left)
                if (i.right):temp2.append(i.right)
            temp = temp2
        return res

——————————————————————————————————————————

可以利用remove或者pop函数,本以为可以省略一个变量,但是发现不行,如果temp实时改变,则for循环不会在树根结点只循环一次,但是非常巧妙地省略了中间的for循环

教训:list.remove(a)返回None,而且参数为列表元素值;list.pop(0)返回删除的元素,而且参数为列表元素下标

运行时间:27ms

占用内存:5728k

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        if not root:
            return []
        temp = [root]
        res = []
        while (temp):
            temp2 = temp.pop(0)
            if(temp2.left):temp.append(temp2.left)
            if (temp2.right):temp.append(temp2.right)
            res.append(temp2.val)
        return res

猜你喜欢

转载自blog.csdn.net/u014381464/article/details/82020154