层次遍历
public class Solution {
public int[] levelPrint(TreeNode root){
if(root == null)
{
return new int[0];
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
LinkedList<Integer> arr = new LinkedList<>();
TreeNode current = null;
queue.offer(root);//将根节点入队
while(!queue.isEmpty())
{
current = queue.poll();//出队队头元素并访问
arr.add(current.val);
//System.out.println(current.val);
if(current.left != null)//如果当前节点的左节点不为空入队
{
queue.offer(current.left);
}
if(current.right != null)//如果当前节点的右节点不为空,把右节点入队
{
queue.offer(current.right);
}
}
int newarr[] = new int[arr.size()];
for(int i=0; i<arr.size(); i++){ //#####特别要注意
// newarr[i]=arr.removeFirst();
newarr[i]=arr.get(i);
}
return newarr;
}
}