我是靠谱客的博主 飞快书本,最近开发中收集的这篇文章主要介绍Leetcode 面试题 04.03.特定深度节点链表Leetcode 面试题 04.03. 特定深度节点链表,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Leetcode 面试题 04.03. 特定深度节点链表

1 题目描述(Leetcode题目链接)

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

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

        1
       /   
      2    3
     /      
    4   5    7
   /
  8

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

2 题解

  二叉树的层次遍历。

# 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]:
        if not tree:
            return []
        queue = collections.deque([tree])
        res = []
        while queue:
            num = len(queue)
            dummy = ListNode(0)
            p = dummy
            while num:
                num -= 1
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                new = ListNode(node.val)
                p.next = new
                p = p.next
            res.append(dummy.next)
        return res

最后

以上就是飞快书本为你收集整理的Leetcode 面试题 04.03.特定深度节点链表Leetcode 面试题 04.03. 特定深度节点链表的全部内容,希望文章能够帮你解决Leetcode 面试题 04.03.特定深度节点链表Leetcode 面试题 04.03. 特定深度节点链表所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部