LeetCode剑指offer Q32——l 从上到下打印二叉树

本文介绍了一种使用队列实现的二叉树层次遍历算法,并提供了两种将List转换为int[]数组的方法,包括使用forEach循环和Arrays的mapToInt映射函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路

简单的层次遍历即可,使用队列进行层次扫描。但是在此过程中需要用到List 集合,但是函数要求的返回值为int[],因此在转换方式上我使用了两种方式,一种就是forEach 直接一个一个的转,另一种就是使用Arrays的mapToInt映射函数,具体的就是Arrays.stream(原来的list).mapToInt(这里填单个元素转换的class中的转换函数,我这里是Integer::valueOf).toArray();

代码

/**
 * 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];
        //Queue<TreeNode> q=new LinkedList<>();
        //q.add(root);
        TreeNode[] q = new TreeNode[2001];
        int start = 0, end = 0;
        q[++end] = root;
        List<Integer> reList = new ArrayList<>();
        while (start != end) {
            TreeNode cursor = q[++start];
            reList.add(cursor.val);
            if (cursor.left != null) q[++end] = cursor.left;
            if (cursor.right != null) q[++end] = cursor.right;
        }
         int[] re=new int[reList.size()];
         for(int i=0;i<re.length;i++)
         re[i]=reList.get(i);
         return re;
        // Integer[] re = new Integer[reList.size()];
        // reList.toArray(re);
        // return Arrays.stream(re).mapToInt(Integer::valueOf).toArray();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值