package com.niuke;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* Created by admin on 2018/3/11.
* 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
*/
public class Print {
ArrayList<ArrayList<Integer>> print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> alist=new ArrayList<>();//存储最终结果
if(pRoot==null) {
return alist;//若为空返回
}
LinkedList<TreeNode> queue=new LinkedList<>();//队列
ArrayList<Integer> list=new ArrayList<>();
queue.add(pRoot);//将根节点加入队列
int count=0;//该层的最左节点
int lastcount=1;//该层的最右节点
while (queue.size()!=0) {//循环直到队列中没有数
TreeNode tmp=queue.removeFirst();//移除队头节点并记录
list.add(tmp.val);
count++;//该层索引右移
if(tmp.left!=null) {//该点左子树不为空将其加到队列
queue.add(tmp.left);
}
if(tmp.right!=null) {//该点右子树不为空将其加到队列
queue.add(tmp.right);
}
if(count==lastcount) {//遍历到该层最后一个节点
lastcount=queue.size();//将最右索引设置为队列的长度,因为现在队列存储的是下一层的所有节点
count=0;//将最左节点重置就为0
alist.add(new ArrayList<Integer>(list));//加打结果中
list.clear();
}
}
return alist;
}
}
把二叉树按层打印成多行
最新推荐文章于 2020-08-13 22:08:14 发布