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

按之字形顺序打印二叉树

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

import java.util.*;



/*
在BFS层次打印的基础上,维护一个深度变量dep。每次将子数组list添加到总数组all中的时候,深度就加1.
    当dep为奇数的时候,使用ArrayList.add(obj)来在尾部追加
    当dep为偶数的时候,使用ArrayList.add(0,obj)来在头部追加
*/
public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
     ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>();
        if(pRoot==null)return all; 
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(pRoot);
        int dep=1;
        while(!queue.isEmpty()){
            ArrayList<Integer> list = new ArrayList<Integer>();
            int size = queue.size();
            for(int i=0;i<size;i++){
                pRoot = queue.poll();

                // 不同的添加方式
                if(dep%2==1) list.add(pRoot.val);
                else if (dep%2==0) list.add(0, pRoot.val);


                if (pRoot.left != null) {
                    queue.offer(pRoot.left);
                }
                if (pRoot.right != null) {
                    queue.offer(pRoot.right);
                }
            }
            all.add(list);
            dep++;
        }
        return all;
    }

}
全部评论

相关推荐

面了100年面试不知...:头像换成柯南再试试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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