Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists).
Example
Given binary tree:
1
/ \
2 3
/
4
return
[
1->null,
2->3->null,
4->null
]
这题可以用bfs和dfs做,bfs是自己写的,dfs是九章的实现。
publicList<ListNode>binaryTreeToLists(TreeNode root) {List<ListNode> res =newArrayList<>();if (root ==null) {return res; }// bfsQueue<TreeNode> queue =newLinkedList<>();queue.offer(root);while (!queue.isEmpty()) {int size =queue.size();ListNode dummy =newListNode(-1);ListNode p = dummy;for (int i =0; i < size; i++) {TreeNode cur =queue.poll();ListNode newNode =newListNode(cur.val);p.next= newNode; p =p.next;if (cur.left!=null) {queue.offer(cur.left); }if (cur.right!=null) {queue.offer(cur.right); } }res.add(dummy.next); }return res;}