# 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 = [tree]
res = [] #存放最后结果的列表
while queue:
lens = len(queue)
#这里定义了每层节点组成的链表的头结点
cur = nex = ListNode(0)
for i in range(lens):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
#对每个节点创建一个节点
tmp = ListNode(node.val)
cur.next = tmp
cur = cur.next
#将每层的头结点的下一个节点存入到列表中
res.append(nex.next)
return res