题目:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:利用队列数据结构来存储结点,每次存入一层的结点。
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
if(pRoot==null){
return a;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
int count = 0;
while(!queue.isEmpty()){
count = queue.size();
ArrayList<Integer> temp = new ArrayList<>();
while(count>0){
TreeNode node =