描述
给一棵二叉树,设计一个算法为每一层的节点建立一个链表。也就是说,如果一棵二叉树有D层,那么你需要创建 D 条链表。
样例
对于二叉树:
1
/ \
2 3
/
4
返回 3 条链表:
[
1->null,
2->3->null,
4->null
]
代码实现
/**
* 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) {
List<ListNode> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
ListNode dummy = new ListNode(0);
ListNode lastNode = null;
//result输出[1-2-3-null, 1-2-3-null,1-2-3-null]
//dummy.next = null;
//lastNode = dummy;
while(!queue.isEmpty()) {
//遍历完一层后重新将dummy和lastNode 初始化
dummy.next = null;
lastNode = dummy;
//TreeNode node = queue.poll();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
lastNode.next = new ListNode(node.val);
lastNode = lastNode.next;
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
result.add(dummy.next);
}
return result;
}
}