Description:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
import java.util.ArrayList;
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 root) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
if (root == null)
return list;
int curCount = 1;
int nextCount = 0;
LinkedList<TreeNode> q = new LinkedList<>();
q.offer(root);
ArrayList<Integer> tmpList = new ArrayList<>();
while (!q.isEmpty()) {
TreeNode node = q.poll();
tmpList.add(node.val);
curCount--;
if (node.left != null) {
q.offer(node.left);
nextCount++;
}
if (node.right != null) {
q.offer(node.right);
nextCount++;
}
if (curCount == 0) {
list.add(tmpList);
tmpList = new ArrayList<>();
curCount = nextCount;
nextCount = 0;
}
}
return list;
}
}