gold-4-3


给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。

示例:

输入:[1,2,3,4,5,null,7,8]

        1
       /  \ 
      2    3
     / \    \ 
    4   5    7
   /
  8

输出:[[1],[2,3],[4,5,7],[8]]

//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode[] listOfDepth(TreeNode tree) {
        List<ListNode> resultList = new ArrayList<>();
        if (tree == null) {
            return new ListNode[0];
        }

        Queue<TreeNode> treeQueue = new LinkedList<>();
        treeQueue.add(tree);

        while (!treeQueue.isEmpty()) {
            int curSize = treeQueue.size();
            ListNode curList = null;
            ListNode preNode = null;

            for (int i = 0; i < curSize; i++) {
                TreeNode treeNode = treeQueue.poll();
                ListNode listNode = new ListNode(treeNode.val);

                if (i == 0) {
                    curList = listNode;
                    preNode = listNode;
                } else {
                    preNode.next = listNode;
                    preNode = listNode;
                }

                if (treeNode.left != null) {
                    treeQueue.add(treeNode.left);
                }
                if (treeNode.right != null) {
                    treeQueue.add(treeNode.right);
                }
            }
            resultList.add(curList);
        }
        return resultList.toArray(new ListNode[resultList.size()]);
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !