给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D
,则会创建出 D
个链表)。返回一个包含所有深度的链表的数组。
示例:
输入:[1,2,3,4,5,null,7,8] 1 / \ 2 3 / \ \ 4 5 7 / 8 输出:[[1],[2,3],[4,5,7],[8]]
层序遍历
class Solution:
def listOfDepth(self, tree: TreeNode) -> List[ListNode]:
q = [tree]
ans = []
while q:
n = len(q)
head = ListNode(-1)
tail = head
for i in range(n):
front = q.pop(0)
node = ListNode(front.val)
tail.next = node
tail = node
if front.left:
q.append(front.left)
if front.right:
q.append(front.right)
ans.append(head.next)
return ans
class Solution {
public ListNode[] listOfDepth(TreeNode tree) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(tree);
List<ListNode> ans = new ArrayList<>();
while (!queue.isEmpty()) {
int n = queue.size();
ListNode head = new ListNode(-1);
ListNode tail = head;
for (int i = 0; i < n; i++) {
TreeNode front = queue.poll();
ListNode node = new ListNode(front.val);
tail.next = node;
tail = node;
if (front.left != null) {
queue.offer(front.left);
}
if (front.right != null) {
queue.offer(front.right);
}
}
ans.add(head.next);
}
return ans.toArray(new ListNode[0]);
}
}
func listOfDepth(tree *TreeNode) []*ListNode {
queue := make([]*TreeNode, 0)
queue = append(queue, tree)
ans := make([]*ListNode, 0)
for len(queue) > 0 {
n := len(queue)
head := new(ListNode)
tail := head
for i := 0; i < n; i++ {
front := queue[0]
queue = queue[1:]
node := &ListNode{Val: front.Val}
tail.Next = node
tail = node
if front.Left != nil {
queue = append(queue, front.Left)
}
if front.Right != nil {
queue = append(queue, front.Right)
}
}
ans = append(ans, head.Next)
}
return ans
}