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

按之字形顺序打印二叉树

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()){
            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);
                    
            }
  
            count++;
            ans.add(new ArrayList<>(list));
            
        }
        return ans;
    }

}
全部评论

相关推荐

02-26 13:56
已编辑
重庆财经学院 Java
King987:你有实习经历,但是写的也太简单了,这肯定是不行的,你主要要包装实习经历这一块,看我的作品,你自己包装一下吧,或者发我,我给你出一期作品
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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