按之字形顺序打印二叉树
按之字形顺序打印二叉树
http://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0
这题其实就是把“二叉树打印成多行”的偶数层反转一下,搞个Collections.reverse(list);就可以了
二叉树打印成多行的地址:https://blog.nowcoder.net/n/0f27800916264398bc7e4c5c16191009
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> thelist = new ArrayList<ArrayList<Integer>>();
if(pRoot==null)return thelist; //这里要求返回thelist而不是null
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(pRoot);
int count = 1;
while(!queue.isEmpty()){
ArrayList<Integer> list = new ArrayList<Integer>();
int size = queue.size();
for(int i=0;i<size;i++){
TreeNode temp = queue.poll();
list.add(temp.val);
if(temp.left!=null)queue.offer(temp.left);
if(temp.right!=null)queue.offer(temp.right);
}
if(count%2==0){
Collections.reverse(list);
thelist.add(list);}
else thelist.add(list);
count++;
}
return thelist;
}
}
查看14道真题和解析