层次遍历:
/**
*
* 面试题 04.03. 特定深度节点链表
*
* 执行用时: 1 ms
* 内存消耗: 36.5 MB
*
*/
public class ListOfDepth {
public ListNode[] listOfDepth(TreeNode tree) {
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(tree);
List<ListNode> res = new ArrayList<ListNode>();
ListNode list = new ListNode(-1);
while(!queue.isEmpty()){
int size = queue.size();
ListNode cur = list;
for(int i = 0;i < size; i++){
TreeNode node = queue.poll();
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
cur.next = new ListNode(node.val);
cur = cur.next;
}
res.add(list.next);
list.next = null;
}
return res.toArray(new ListNode[]{});
}
}