打卡群刷题总结0808——二叉树的层序遍历

时间:2022-07-23
本文章向大家介绍打卡群刷题总结0808——二叉树的层序遍历,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目:102. 二叉树的层序遍历

链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。(即逐层地,从左到右访问所有节点)。 示例: 二叉树:[3,9,20,null,null,15,7], 3 / 9 20 / 15 7 返回其层次遍历结果: [ [3], [9,20], [15,7] ]

解题:

1、队列,先进先出。

代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        res = []
        nodes = [root]
        while len(nodes) > 0:
            tmp = []
            vals = []
            for node in nodes:
                vals.append(node.val)
                if node.left:
                    tmp.append(node.left)
                if node.right:
                    tmp.append(node.right)
            nodes = copy.copy(tmp)
            res.append(vals)
        return res

PS:刷了打卡群的题,再刷另一道题,并且总结,确实耗费很多时间。如果时间不够,以后的更新会总结打卡群的题。

PPS:还是得日更呀,总结一下总是好的。