分析,与题目107非常像,最大的不同是输出结果是自顶向下的,不需要新设计list变量,反向结果,直接输出即可
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int count(TreeNode x)
{
if(x==null)
return 0;
else
{
int lc=count(x.left);
int rc=count(x.right);
return lc+rc+1;
}
}
int height(TreeNode x)
{
if(x==null)
return 0;
else
{
int lh=height(x.left);
int rh=height(x.right);
if(lh>rh)
return lh+1;
else
return rh+1;
}
}
TreeNode[] queue;
int start=0;
int end=0;
int size=0;
void enqueue(TreeNode x)
{
queue[start]=x;
//if(isEmpty())
// end=(end+1)%size;
start=(start+1)%size;
}
TreeNode outqueue()
{
//start=(start-1)%size;
end=(end+1)%size;
return queue[(end-1)%size];
}
boolean isEmpty()
{
if(end==start)
return true;
else
return false;
}
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> listl=new ArrayList<List<Integer>>();
List<List<Integer>> listend=new ArrayList<List<Integer>>();
size=(count(root)+1)*10;
int H=height(root);
//List<Integer>[] v;
//for(int i=0;i<H;i++)
// v[i]=new ArrayList<Integer>();
queue=new TreeNode[size];
for(int i=0;i<size;i++)
queue[i]=new TreeNode(0);
TreeNode y=null;
enqueue(root);
enqueue(y);
int c=0;
while(!isEmpty())
{
boolean t=false;
List<Integer> l=new ArrayList<Integer>();
TreeNode z=outqueue();
while(z!=null)
{
l.add(z.val);
if(z.left!=null)
{
enqueue(z.left);
t=true;
}
if(z.right!=null)
{
enqueue(z.right);
t=true;
}
z=outqueue();
}
if(!l.isEmpty())
listl.add(l);
if(t)
{
enqueue(y);
c++;
}
}
for(int j=listl.size()-1;j>=0;j--)
listend.add(listl.get(j));
return listl;
}
}