按字形顺序打印二叉树

按之字形顺序打印二叉树

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

public class Solution {


    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer> > res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        //使用标记 是从左往右还是 从右往左
        boolean flag = true;
        if(pRoot != null)
            queue.offer(pRoot);
        int size = 0;
        while(!queue.isEmpty()){
            ArrayList<Integer> temp = new ArrayList<>();
            size = queue.size();
            for(int i = 0; i < size; i++){
                TreeNode tmp = queue.poll();
                if(tmp == null) continue;
                if(flag){
                    //尾插入法
                    temp.add(tmp.val);
                }else{
                    //头插入法
                    temp.add(0, tmp.val);
                }

                if(tmp.left != null)
                    queue.offer(tmp.left);
                if(tmp.right != null)
                    queue.offer(tmp.right);
            }
            if(temp.size() != 0){
                res.add(new ArrayList<Integer>(temp));
            }
            flag =! flag;

        }
        return res;
    }

}
全部评论

相关推荐

04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
05-05 21:45
已编辑
广州大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务