写着自己看看
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list=new LinkedList<>();
if (root==null)
return list;
Queue<TreeNode> queue=new ArrayDeque<>();
queue.add(root);
while(!queue.isEmpty()){
List<Integer> l=new LinkedList<>();
int len=queue.size();
for (int i = 0; i <len; i++) {
TreeNode left=queue.poll();
l.add(left.val);
if (left.left!=null){
queue.add(left.left);
}
if (left.right!=null){
queue.add(left.right);
}
}
list.add(l);
}
return list;
}
递归更快
List<List<Integer>> li=new ArrayList<>();
public List<List<Integer>> levelOrder1(TreeNode root) {
if (root==null)
return li;
helper(root,0);
return li;
}
public void helper(TreeNode root, int level){
if (li.size()==level)
li.add(new ArrayList<>());
li.get(level).add(root.val);
if (root.left!=null)
helper(root.left,level+1);
if (root.right!=null)
helper(root.right,level+1);
}