从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
import java.util.ArrayList;
import java.util.LinkedList;
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>> level = new ArrayList<>();
ArrayList<Integer> arrays = new ArrayList<>();
LinkedList<TreeNode> queue = new LinkedList<>();
if (pRoot == null) {
return level;
}
queue.add(pRoot);
TreeNode current = null;
TreeNode last = pRoot;//正在打印的当前行的最右节点
TreeNode nlast = null;//表示下一行的最右节点
while (queue.size() != 0) {
current = queue.poll();
arrays.add(current.val);
if (current.left != null) {
queue.add(current.left);
nlast = current.left;
}
if (current.right != null) {
queue.add(current.right);
nlast = current.right;
}
if (current == last) {
level.add(arrays);
arrays = new ArrayList<>();
last = nlast;
}
}
return level;
}
}