题目
ArrayList.remove底层是使用的是native system.arrayCopy()直接把原数组复制过去。所以移除的时候只能移除第一个元素。
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
// write code here
ArrayList<ArrayList<Integer>>list = new ArrayList<>();
ArrayList<TreeNode>treeList=new ArrayList<>();
if(root==null){
return list;
}
treeList.add(root);
while (!treeList.isEmpty()){
int size=treeList.size();
ArrayList<Integer>subList=new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node=treeList.remove(0);
subList.add(node.val);
if(node.left!=null){
treeList.add(node.left);
}
if(node.right!=null){
treeList.add(node.right);
}
}
list.add(subList);
}
return list;
}
}