【剑指offer】把二叉树打印成多行
把二叉树打印成多行
http://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
1、思路分析
因为每层的结点均是从左往右打印,所以只需要用一个队列来进行存储即可,需要注意的是,题目要求每一层输出一行,为了区别不同的行数,需要记录当前层和下一层的结点数。采取添加-移除-添加的方式。
2、代码
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
ArrayList<Integer> tmp = new ArrayList<>();
LinkedList<TreeNode> tn = new LinkedList<>();
if(pRoot == null) {
return res;
}
tn.add(pRoot);
int now = 1, next = 0;
while(!tn.isEmpty()) {
TreeNode t = tn.remove();
now--;
tmp.add(t.val);
if(t.left != null) {
tn.add(t.left);
next++;
}
if(t.right != null) {
tn.add(t.right);
next++;
}
if(now == 0) {
res.add(new ArrayList<Integer>(tmp));
tmp.clear();
now = next;
next = 0;
}
}
return res;
}
}
海康威视公司氛围 920人发布