剑指offer算法题
二叉树 层次遍历
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
题目分析
利用层次遍历,每次遍历将节点的值加入ArrayList < Integer > 中,完成一层遍历后加入 ArrayList<ArrayList < Integer > >
中。
注意每次完成遍历后不要使用clear清空arraylist,因为是传递的引用,用clear会清空我们所添加的内容。
下面是JAVA算法实现:
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer>>();
if(pRoot == null){
return result;
}
Queue<TreeNode> q = new LinkedList<>();
ArrayList<Integer> array = new ArrayList<>();
int count = 0, nextCount = 1;
q.offer(pRoot);
while(!q.isEmpty()){
TreeNode tmp = q.poll();
array.add(tmp.val);
++count;
if(tmp.left!=null){
q.offer(tmp.left);
}
if(tmp.right!=null){
q.offer(tmp.right);
}
if(count == nextCount){
count = 0;
nextCount = q.size();
result.add(array);
//注意不要用array.clear(),因为添加的是引用,如果clear的话会清空result中的内容。
array = new ArrayList<>();
}
}
return result;
}