利用层次遍历的算法,设置变量last指向当前层的最后一个节点,设置变量count记录当前层已经访问的节点的个数,当count等于last时,表示该层访问结束。
层次遍历在求树的宽度、输出某一层节点,某一层节点个数,每一层节点个数都可以采取类似的算法。
树的宽度:在树的深度算法基础上,加一个记录访问过的层节点个数最多的变量max,在访问每层前max与last比较,如果max比较大,max不变,如果max小于last,把last赋值给max;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot)
{
ArrayList<ArrayList<Integer>> list1 = new ArrayList<ArrayList<Integer>>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
if(pRoot == null)
{
return list1;
}
TreeNode current = pRoot;
queue.offer(current);
int count;//记录当前层已经打印的个数
int last;//记录当前层一个有多少个
while(!queue.isEmpty())
{
count = 0;
last = queue.size();
ArrayList<Integer> list2 = new ArrayList<Integer>();
//打印一层
while(count < last)
{
current = queue.pop();//出队一个节点并将气质加入到list2中
list2.add(current.val);
count++;//每出队一个几点就增加一个当前层已经打印的节点个数
if(current.left != null)
queue.offer(current.left);
if(current.right != null)
queue.offer(current.right);
}
list1.add(list2);
}
return list1;
}
}