JZ78 把二叉树打印成多行
把二叉树打印成多行_牛客题霸_牛客网 (nowcoder.com)
NC15 求二叉树的层序遍历
求二叉树的层序遍历_牛客题霸_牛客网 (nowcoder.com)
import java.util.*;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode root) {
ArrayList<ArrayList<Integer>> ret=new ArrayList<>();
if(root==null){
return ret;
}
Queue<TreeNode> q=new LinkedList<>();
q.offer(root);
while(q.isEmpty()==false){
ArrayList<Integer> list=new ArrayList<>();
int n=q.size();
for(int i=0;i<n;i++){
TreeNode cur=q.poll();
list.add(cur.val);
if(cur.left!=null){
q.offer(cur.left);
}
if(cur.right!=null){
q.offer(cur.right);
}
}
ret.add(list);
}
return ret;
}
}