按字形顺序打印二叉树
按之字形顺序打印二叉树
http://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
//使用标记 是从左往右还是 从右往左
boolean flag = true;
if(pRoot != null)
queue.offer(pRoot);
int size = 0;
while(!queue.isEmpty()){
ArrayList<Integer> temp = new ArrayList<>();
size = queue.size();
for(int i = 0; i < size; i++){
TreeNode tmp = queue.poll();
if(tmp == null) continue;
if(flag){
//尾插入法
temp.add(tmp.val);
}else{
//头插入法
temp.add(0, tmp.val);
}
if(tmp.left != null)
queue.offer(tmp.left);
if(tmp.right != null)
queue.offer(tmp.right);
}
if(temp.size() != 0){
res.add(new ArrayList<Integer>(temp));
}
flag =! flag;
}
return res;
}
}
查看4道真题和解析
美的集团公司福利 819人发布