题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行
import java.util.ArrayList;
import java.util.Deque;
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>> arrayList = new ArrayList<ArrayList<Integer>>();
if(pRoot == null)
return arrayList;
Deque<TreeNode> deque = new LinkedList<TreeNode>();
ArrayList<Integer> list = new ArrayList<Integer>();
deque.add(pRoot);
int noPrint = 1; //当前层中未打印的节点数
int nextPrint = 0; //下一层要打印的节点数
while (!deque.isEmpty()) {
TreeNode t = deque.pop();
list.add(t.val);
if(t.left != null){
deque.add(t.left);
++nextPrint;
}
if(t.right != null) {
deque.add(t.right);
++nextPrint;
}
--noPrint;
//当一层遍历完成时,将此层的所有数据放入arrayList ,并清空list,用于保存下一层数据;将剩余未打印节点数置为下一层要打印的节点数,将下一层要打印的节点数重置为0
if (noPrint == 0) {
arrayList.add(new ArrayList<>(list));
list.clear();
noPrint = nextPrint; //
nextPrint = 0;
}
}
return arrayList;
}
}