题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
if(pRoot == null){
return new ArrayList<>();
}
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
//记录第几层,从0层开始
int count = 0;
while(!queue.isEmpty()){
for(int i = 0;i<size;i++){
list.addFirst(cur.val);
}
if(cur.left!=null)
queue.add(cur.left);
if(cur.right!=null)
queue.add(cur.right);
count++;
ans.add(new ArrayList<>(list));
}
return ans;
}
}
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
if(pRoot == null){
return new ArrayList<>();
}
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
//记录第几层,从0层开始
int count = 0;
while(!queue.isEmpty()){
int size = queue.size();
//记录每一层值
LinkedList<Integer> list = new LinkedList<>();for(int i = 0;i<size;i++){
TreeNode cur = queue.poll();
//偶数层从后面加入
if(count%2==0){
list.addLast(cur.val);
//奇数层从前面加入
}else{list.addFirst(cur.val);
}
if(cur.left!=null)
queue.add(cur.left);
if(cur.right!=null)
queue.add(cur.right);
}
ans.add(new ArrayList<>(list));
}
return ans;
}
}
查看14道真题和解析