题目:
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 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 {
ArrayList<ArrayList<ListNode>> res = new ArrayList<>();
public ListNode[] listOfDepth(TreeNode tree) {
dfs(tree, 0);
ListNode[] resArr = new ListNode[res.size()];
for (int j = 0, resSize = res.size(); j < resSize; j++) {
ArrayList<ListNode> deepList = res.get(j);
for (int i = 0; i < deepList.size(); i++) {
if (i == 0) {
resArr[j] = deepList.get(i);
} else {
deepList.get(i - 1).next = deepList.get(i);
}
}
}
return resArr;
}
private void dfs(TreeNode tree, int index) {
if (tree == null) return;
if (res.size() <= index) {
res.add(index, new ArrayList<>());
}
ArrayList<ListNode> listNodes = res.get(index);
listNodes.add(new ListNode(tree.val));
dfs(tree.left, index + 1);
dfs(tree.right, index + 1);
}
}