题目
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
解题思路:
1.使用队列,BFS
【这就是数的层次遍历,加多了个逻辑(将每层形成链表存储到arrayList中…)】
- 树的层次遍历的方式,将节点的左子树和右子树都存进队列
- 将同在一层的节点组成ListNode链表
- 将头结点存进ArrayList中
- 最后将ArrayList中的头结点存到ListNode[]数组中进行返回
public class Test {
public static void main(String[] args) {
//[1,2,3,4,5,null,7,8]
TreeNode head = new TreeNode(1);
head.left = new TreeNode(2);
head.right = new TreeNode(3);
head.left.left = new TreeNode(4);
head.left.right = new TreeNode(5);
head.left.left.left = new TreeNode(8);
head.right.right = new TreeNode(7);
ListNode[] solution = solution(head);
System.out.println(solution[1].next.val);
System.out.println(solution[2].val);
}
public static ListNode[] solution(TreeNode head) {
if (head == null) {
return new ListNode[0];
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(head);
List<ListNode> list = new ArrayList<>();
ListNode headp = null, tmp = new ListNode(0);
int len = 0;
while (!queue.isEmpty()) {
for (int size = queue.size(); size > 0; size--) {
TreeNode poll = queue.poll();
if (poll.left != null) {
queue.add(poll.left);
}
if (poll.right != null) {
queue.add(poll.right);
}
tmp.val = poll.val;
if (len == 0) {
headp = tmp;
}
if (size == 1) {
//如果是最后一次遍历,那么就不创建新节点了。
continue;
}
tmp.next = new ListNode(0);
tmp = tmp.next;
len++;
}
list.add(headp);
len = 0;
tmp = new ListNode(0);
}
ListNode[] res = new ListNode[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
}
性能:
时间复杂度是O(n2),空间复杂度用到了队列和链表所以是O(n)