原题目
面试题 04.03. 特定深度节点链表
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D
,则会创建出 D
个链表)。返回一个包含所有深度的链表的数组。
示例:
输入:[1,2,3,4,5,null,7,8]
1
/ \
2 3
/ \ \
4 5 7
/
8
输出:[[1],[2,3],[4,5,7],[8]]
第一遍解法
BFS,树的层次遍历。在while中的for循环遍历的元素都是在同一层,且顺序,然后依次加入链表即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode[] listOfDepth(TreeNode tree) {
List<ListNode> listNodeList = new ArrayList();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(tree);
while (!queue.isEmpty()) {
ListNode head = null;
ListNode cur = null; // 方便尾插
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode treeNode = queue.poll();
if (i == 0) {
head = new ListNode(treeNode.val);
cur = head;
} else {
cur.next = new ListNode(treeNode.val);
cur = cur.next;
}
if (treeNode.left != null) {
queue.offer(treeNode.left);
}
if (treeNode.right != null) {
queue.offer(treeNode.right);
}
}
listNodeList.add(head);
}
// List to Array
ListNode[] listNodeArray = new ListNode[listNodeList.size()];
return listNodeList.toArray(listNodeArray);
}
}
时间复杂度: O(n)
空间复杂度: O(n)
小结
-
LinkedList为队列集合,使用offer入队,poll出队。(add和remove会抛出异常)
-
List转数组时,不能直接toArray(),这会返回Object[]对象,应先根据List的大小new一个数组,然后将其加入toArray的参数中。
// Error String strArray = strList.toArray(); // Right String[] strArray = new String[strList.size()]; strArray = strList.toArray(strArray);