不难,但是最后强制类型转化费了不少功夫。
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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
参考博客: