题目
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
示例
输入:[1,2,3,4,5,null,7,8]
1
/ \
2 3
/ \ \
4 5 7
/
8
输出:[[1],[2,3],[4,5,7],[8]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/list-of-depth-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:BFS
Java实现
class Solution {
public ListNode[] listOfDepth(TreeNode tree) {
List<ListNode> res = new ArrayList<>();
if (tree == null) return new ListNode[]{};
Queue<TreeNode> q = new LinkedList<>();
q.offer(tree);
while (!q.isEmpty()) {
int sz = q.size();
ListNode dummy = new ListNode();
ListNode pre = dummy;
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
pre.next = new ListNode(cur.val);
pre = pre.next;
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
res.add(dummy.next);
}
ListNode[] out = new ListNode[res.size()];
for (int i = 0; i < res.size(); i++) out[i] = res.get(i);
return out;
}
}