按之字形顺序打印二叉树

按之字形顺序打印二叉树

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;    
    }

}
全部评论
if(pRoot==null)return thelist; //这里要求返回thelist而不是null,这里为什么呢?
点赞 回复 分享
发布于 2020-07-24 11:26
小杨超越就是厉害
点赞 回复 分享
发布于 2020-07-24 11:25

相关推荐

caicaidog:现实里没实习的还是占多数的
点赞 评论 收藏
分享
03-03 23:12
已编辑
北京邮电大学 Java
书海为家:我来给一点点小建议,因为毕竟还在学校不像工作几年的老鸟有丰富的项目经验,面试官在面试在校生的时候更关注咱们同学的做事逻辑和思路,所以最好在简历中描述下自己做过项目的完整过程,比如需求怎么来的,你对需求的解读,你想到的解决办法,遇到困难如何找人求助,最终项目做成了什么程度,你从中收获了哪些技能,你有什么感悟。
你的简历改到第几版了
点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务