LeetCode | 面试题 04.03. 特定深度节点链表【Python】

问题

力扣

给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。

示例:

输入:[1,2,3,4,5,null,7,8]
        1
       /  \ 
      2    3
     / \    \ 
    4   5    7
   /
  8

输出:[[1],[2,3],[4,5,7],[8]]

思路

BFS

层次遍历,每层节点单独构成一个单链表。

代码

Python3

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def listOfDepth(self, tree: TreeNode) -> List[ListNode]:
        import collections

        if not tree:
            return []

        queue = collections.deque()
        queue.append(tree)
        res = []
        # BFS
        while queue:
            n = len(queue)
            for i in range(n):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                # 当前层的第一个节点
                if i == 0:
                    # 头节点
                    head = ListNode(node.val)
                    tmp = head
                else:
                    tmp.next = ListNode(node.val)
                    tmp = tmp.next
            # 这里加入res的是head
            res.append(head)
        return res

链接

GitHub

LeetCode个人题解 文章被收录于专栏

LeetCode个人题解,目前主要是 Python3 题解。

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-27 15:19
简历上能写3个月吗?
码农索隆:大胆写,主要你能把实习经历包装好,可以看一下我这篇帖子https://www.nowcoder.com/share/jump/4888395581180798063
点赞 评论 收藏
分享
zYvv:双一流加大加粗再标红,然后广投。主要是获奖荣誉不够,建议开始不用追求大厂,去别的厂子刷下实习。
点赞 评论 收藏
分享
喜欢飞来飞去的雪碧在...:可以试一试字节
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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