题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0


// 层次遍历题目加上一个判断,当层数是偶数的时候翻转一下结果
public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        int count = 1;
        // 定义一个队列
        LinkedList<TreeNode> duiLie = new LinkedList<>();
        // 根节点入队列
        if(pRoot != null)
        duiLie.add(pRoot);
        // 定义出队节点个数
        int outCount = 0;
        // 定义返回队列
        ArrayList<ArrayList<Integer> >  returnList = new ArrayList<>();
        // 开始遍历
        while(!duiLie.isEmpty()){
            outCount = duiLie.size(); // 记录这一层的个数
            // 定义list 保存遍历结果
            ArrayList<Integer> outCome = new ArrayList<>();
            for(int i = 0; i< outCount; i++){ // 这一层出队
                TreeNode del = duiLie.removeFirst();
                outCome.add(del.val);
                // 下一层入队
                if(del.left != null)
                    duiLie.add(del.left);
                if(del.right != null)
                    duiLie.add(del.right);
            }
            if(count % 2 == 0){
                Collections.reverse(outCome);
            }
            count++;
            returnList.add(outCome);
            }
        return returnList;
    }
}
全部评论

相关推荐

07-09 12:12
门头沟学院 Java
5月底投简历7月初开奖收获秋招第一个offer,虽然白菜价,但至少能保底了
土木转行ing:土木博士想转图像,最后拿了 tp 提前批 sp 最低档,感觉性价比不高
TP-LINK开奖132人在聊
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 12:10
点赞 评论 收藏
分享
写不来代码的小黑:这么小的城市能有做it的公司也不容易
点赞 评论 收藏
分享
07-09 19:25
门头沟学院 Java
这是要把每一个投校招的都开盒吗?
26届之耻将大局逆转:裁人的时候一次性追回餐费
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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