题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
import java.util.*;
/*
在BFS层次打印的基础上,维护一个深度变量dep。每次将子数组list添加到总数组all中的时候,深度就加1.
当dep为奇数的时候,使用ArrayList.add(obj)来在尾部追加
当dep为偶数的时候,使用ArrayList.add(0,obj)来在头部追加
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>();
if(pRoot==null)return all;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(pRoot);
int dep=1;
while(!queue.isEmpty()){
ArrayList<Integer> list = new ArrayList<Integer>();
int size = queue.size();
for(int i=0;i<size;i++){
pRoot = queue.poll();
// 不同的添加方式
if(dep%2==1) list.add(pRoot.val);
else if (dep%2==0) list.add(0, pRoot.val);
if (pRoot.left != null) {
queue.offer(pRoot.left);
}
if (pRoot.right != null) {
queue.offer(pRoot.right);
}
}
all.add(list);
dep++;
}
return all;
}
}
汤臣倍健公司氛围 396人发布
查看4道真题和解析