剑指32 - I——从上到下打印二叉树(toArray方法强制转换,将Integer[]转换为int[]数组)

不难,但是最后强制类型转化费了不少功夫。

List容器类中有一个toArray()的方法,该方法是用来把List转化为数组的。

该方法有两种使用形式:toArray()与toArray(T[] t):
toArray()的返回值是一个Object的数组,Object[],这个数组是不可以进行强制数据转换的

所以像这种情况就要用第二种形式来转换:
toArray(T[] t)方法返回一个类T的数组,这个数组包含了类T中的所有元素。这个方法的特点是:如果数组t的长度(创建数组t的时候定义)能够装下整个List的数据的时候,所有数据会被放入数组t中。

例如:

这里写图片描述

如果数组t的长度不够长,那么就会返回一个新的数组。
例如:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] levelOrder(TreeNode root) {

        Queue<TreeNode> queue1 = new LinkedList<>();
        Queue<Integer> queue2 = new LinkedList<>();

        if(root == null) return new int[0];

        queue1.add(root);
        TreeNode tmp;
        
        while(queue1.peek() != null){
            tmp =  queue1.poll();
            if(tmp.left != null) queue1.add(tmp.left);
            if(tmp.right != null) queue1.add(tmp.right);
            queue2.add(tmp.val);
        }
        
        // int[] ans = queue2.toArray(new int[queue2.size()]);

        Integer[] ans = new Integer[queue2.size()];
        queue2.toArray(ans);

        // return queue2.toArray(new Integer[queue2.size()]);
        // return ans;

        return Arrays.stream(ans).mapToInt(Integer::valueOf).toArray();
    }
}

官解优化:

用List存数,可直接通过下标按顺序读取。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] levelOrder(TreeNode root) {
        if(root == null) return new int[0];
        List<Integer> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()) {
            
            TreeNode poll = queue.poll();
            
            list.add(poll.val);
            if(poll.left != null) {
                queue.add(poll.left);
            }
            if(poll.right != null) {
                queue.add(poll.right);
            }
               
            
        }
        int[] target = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            target[i] = list.get(i);
        }
        return target;
    }
}

作者:bobby996
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/solution/jian-zhi-offer32-iti-9975-9027-by-bobby9-5kz5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

参考博客:

List的toArray方法强制转换

Java8<将Integer[]转换为int[]数组>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值