给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
示例:
输入:[1,2,3,4,5,null,7,8]
输出:[[1],[2,3],[4,5,7],[8]]
Python 解答:
# 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]:
lis = []
if not tree:
return []
queue = [tree]
while queue:
root = ListNode(0)
p = root
temp = []
for node in queue:
new = ListNode(node.val)
p.next = new
p = new
if node.left:
temp.append(node.left)
if node.right:
temp.append(node.right)
lis.append(root.next)
queue = temp
return lis
留言