领扣LintCode算法问题答案-242. 将二叉树按照层级转化为链表
目录
- 242. 将二叉树按照层级转化为链表
- 鸣谢
242. 将二叉树按照层级转化为链表
给一棵二叉树,设计一个算法为每一层的节点建立一个链表。也就是说,如果一棵二叉树有 D 层,那么你需要创建 D 条链表。
样例 1:
输入: {1,2,3,4}
输出: [1->null,2->3->null,4->null]
解释:
复制代码
1
2
3
4
5
61 / 2 3 / 4
样例 2:
输入: {1,#,2,3}
输出: [1->null,2->null,3->null]
解释:
复制代码
1
2
3
4
5
61 2 / 3
复制代码
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
47
48
49
50
51
52/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { /** * @param root the root of binary tree * @return a lists of linked list */ public List<ListNode> binaryTreeToLists(TreeNode root) { // Write your code here List<ListNode> listNodes = new ArrayList<ListNode>(); if (root != null) { Queue<TreeNode> nodes = new LinkedList<TreeNode>(); nodes.add(root); ListNode head = new ListNode(0); while (!nodes.isEmpty()) { int size = nodes.size(); ListNode lastNode = head; while (size-- > 0) { TreeNode treeNode = nodes.poll(); lastNode.next = new ListNode(treeNode.val); lastNode = lastNode.next; if (treeNode.left != null) { nodes.offer(treeNode.left); } if (treeNode.right != null) { nodes.offer(treeNode.right); } } listNodes.add(head.next); } } return listNodes; } }
原题链接点这里
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。
最后
以上就是大方大炮最近收集整理的关于领扣LintCode算法问题答案-242. 将二叉树按照层级转化为链表242. 将二叉树按照层级转化为链表鸣谢的全部内容,更多相关领扣LintCode算法问题答案-242.内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复