题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
// 层次遍历题目加上一个判断,当层数是偶数的时候翻转一下结果
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
int count = 1;
// 定义一个队列
LinkedList<TreeNode> duiLie = new LinkedList<>();
// 根节点入队列
if(pRoot != null)
duiLie.add(pRoot);
// 定义出队节点个数
int outCount = 0;
// 定义返回队列
ArrayList<ArrayList<Integer> > returnList = new ArrayList<>();
// 开始遍历
while(!duiLie.isEmpty()){
outCount = duiLie.size(); // 记录这一层的个数
// 定义list 保存遍历结果
ArrayList<Integer> outCome = new ArrayList<>();
for(int i = 0; i< outCount; i++){ // 这一层出队
TreeNode del = duiLie.removeFirst();
outCome.add(del.val);
// 下一层入队
if(del.left != null)
duiLie.add(del.left);
if(del.right != null)
duiLie.add(del.right);
}
if(count % 2 == 0){
Collections.reverse(outCome);
}
count++;
returnList.add(outCome);
}
return returnList;
}
}