题目
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路
用一个布尔量控制从左到右还是从右到左的顺序;如果为真则他的左右孩子按照从左到右的顺序放入list中,否则按照从右到左的顺序,当本行结束之后,再把list中的数据放入一个result中。其中用一个null值作为层次的分隔符。
此处利用LinkList的双向指针特性
每次到达null分层点时,会将null后的点按要求加入result,并且移除null点,并在queue点后加入null
遇到非null点时,将其左右节点加入queue
实现
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result=new ArrayList<ArrayList<Integer> >();
if (pRoot==null){
return result;
}
ArrayList<Integer> list = new ArrayList<Integer>();
LinkedList<TreeNode> queue = new LinkedList<>();
queue.addLast(null);//尾部插入null作为分层标志
queue.addLast(pRoot);
boolean leftToRight = true;
while(queue.size() != 1){ //当size=1时,结束,因为它已经被上次遍历加入到result中
TreeNode temp = queue.removeFirst();//移除并获取第一个元素
if(temp == null){
Iterator iter = null;
if(leftToRight){
iter = queue.iterator();//前往后遍历
}else {
iter = queue.descendingIterator();//后往前遍历
}
leftToRight = !leftToRight;
while(iter.hasNext()){
TreeNode i = (TreeNode)iter.next();
Integer num = i.val;
list.add(num);
}
result.add(new ArrayList(list));
list.clear();
queue.addLast(null);//加入分层标志,此层已被加入result,为了遍历下一层
continue;
}
if(temp.left != null){
queue.addLast(temp.left);
}
if(temp.right != null){
queue.addLast(temp.right);
}
}
return result;
}
}