题目地址:
https://www.lintcode.com/problem/convert-binary-tree-to-linked-lists-by-depth/description
给定一个二叉树,要求将其每一层都按照层序遍历的顺序做成一个单链表,最后返回List of ListNodes。
直接用层序遍历即可。代码如下:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
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> lists = new ArrayList<>();
if (root == null) {
return lists;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
for (int i = 0; i < size; i++) {
TreeNode x = queue.poll();
cur.next = new ListNode(x.val);
cur = cur.next;
if (x.left != null) {
queue.offer(x.left);
}
if (x.right != null) {
queue.offer(x.right);
}
}
lists.add(dummy.next);
}
return lists;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
时空复杂度 O ( n ) O(n) O(n)。