04.03 特定深度节点链表

原题目

面试题 04.03. 特定深度节点链表

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

示例:

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

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

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



第一遍解法

BFS,树的层次遍历。在while中的for循环遍历的元素都是在同一层,且顺序,然后依次加入链表即可。

/**
 * 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> listNodeList = new ArrayList();
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(tree);
        
        while (!queue.isEmpty()) {
            ListNode head = null;
            ListNode cur = null;  // 方便尾插
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.poll(); 
                if (i == 0) {
                    head = new ListNode(treeNode.val);
                    cur = head;
                } else {
                    cur.next = new ListNode(treeNode.val);
                    cur = cur.next;
                }

                if (treeNode.left != null) {
                    queue.offer(treeNode.left);
                }
                if (treeNode.right != null) {
                    queue.offer(treeNode.right);
                }
            }
            listNodeList.add(head);
        }

        // List to Array
        ListNode[] listNodeArray = new ListNode[listNodeList.size()];
        return listNodeList.toArray(listNodeArray);
    }
}

时间复杂度: O(n)

空间复杂度: O(n)



小结

  • LinkedList为队列集合,使用offer入队,poll出队。(add和remove会抛出异常)

  • List转数组时,不能直接toArray(),这会返回Object[]对象,应先根据List的大小new一个数组,然后将其加入toArray的参数中。

    // Error
    String strArray = strList.toArray();
    
    // Right
    String[] strArray = new String[strList.size()];
    strArray = strList.toArray(strArray);
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值