我是靠谱客的博主 执着嚓茶,这篇文章主要介绍leetcode面试题 04.03. 特定深度节点链表(bfs),现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。 示例: 输入:[1,2,3,4,5,null,7,8] 1 / 2 3 / 4 5 7 / 8 输出:[[1],[2,3],[4,5,7],[8]]

代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/** * 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) { Queue<TreeNode> queue=new LinkedList<>(); ArrayList<ListNode> arrayList=new ArrayList<>(); queue.add(tree); while (!queue.isEmpty()) { int size=queue.size(); ListNode head=new ListNode(0);//建立一个辅助的头节点 ListNode helper=head; for(int i=0;i<size;i++) { TreeNode temp=queue.poll(); ListNode temp2=new ListNode(temp.val); helper.next=temp2; helper=temp2; if(temp.left!=null) queue.offer(temp.left); if(temp.right!=null) queue.offer(temp.right); } arrayList.add(head.next); } ListNode[] listNodes=new ListNode[arrayList.size()]; for(int i=0;i<arrayList.size();i++) listNodes[i]=arrayList.get(i); return listNodes; } }

最后

以上就是执着嚓茶最近收集整理的关于leetcode面试题 04.03. 特定深度节点链表(bfs)的全部内容,更多相关leetcode面试题内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(70)

评论列表共有 0 条评论

立即
投稿
返回
顶部