# 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]:
'''
广度优先搜索
'''
res = []
q = collections.deque()
q.append(tree)
while q:
head = ListNode(-1)
cur = head
for i in range(len(q)):
node = q.popleft()
cur.next = ListNode(node.val)
cur = cur.next
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(head.next)
return res
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func listOfDepth(tree *TreeNode) []*ListNode {
queue := []*TreeNode{tree}
ans := []*ListNode{}
for len(queue) > 0 {
size := len(queue)
list := &ListNode{}
curr := list
for i := 0; i < size; i++ {
node := queue[0]
queue = queue[1:]
curr.Next = &ListNode{Val:node.Val}
curr = curr.Next
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil{
queue = append(queue, node.Right)
}
}
ans = append(ans, list.Next)
}
return ans
}