1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. /**
    11. * Definition for singly-linked list.
    12. * public class ListNode {
    13. * int val;
    14. * ListNode next;
    15. * ListNode(int x) { val = x; }
    16. * }
    17. */
    18. class Solution {
    19. public ListNode[] listOfDepth(TreeNode tree) {
    20. // 存放结果的 ListNode List
    21. List<ListNode> ans = new ArrayList();
    22. // bfs用队列
    23. LinkedList<TreeNode> queue = new LinkedList();
    24. // 将起始节点放入队列
    25. queue.addLast(tree);
    26. while(!queue.isEmpty()) {
    27. // 当前层需要遍历的节点次数
    28. int size = queue.size();
    29. // 用于遍历链表的头指针
    30. ListNode head = null;
    31. for (int i = 0; i < size; i++) {
    32. TreeNode tmp = queue.pollFirst();
    33. if (tmp.left != null) {
    34. // tmp节点有左子树,则加到队列
    35. queue.addLast(tmp.left);
    36. }
    37. if (tmp.right != null) {
    38. // tmp节点有右子树,则加到队列
    39. queue.addLast(tmp.right);
    40. }
    41. if (i == 0) {
    42. // 说明另起一行(遍历到某层的第一个元素)
    43. head = new ListNode(tmp.val);
    44. ans.add(head);
    45. } else {
    46. head.next = new ListNode(tmp.val);
    47. head = head.next;
    48. }
    49. }
    50. }
    51. return ans.toArray(new ListNode[0]);
    52. }
    53. }