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

按之字形顺序打印二叉树

https://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 {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return int整型ArrayList<ArrayList<>>
     */
     
    private ArrayList reverseList(ArrayList<Integer> temp){
        ArrayList<Integer> rtemp = new ArrayList<Integer>();
        for(int i=temp.size()-1;i>=0;i--){
            rtemp.add(temp.get(i));
        }
        return rtemp;
    }   
    
    public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
        // write code here
        ArrayList<ArrayList<Integer>> list = new ArrayList();
        if (pRoot == null) return list;

        Queue<TreeNode> q = new ArrayDeque<TreeNode>();
        q.add(pRoot);
        int k = 1;
        while (!q.isEmpty()) {
            ArrayList<Integer> temp = new ArrayList<Integer>();
            int n = q.size();
            for (int i = 0; i < n; i++) {
                TreeNode cur = q.poll();
                temp.add(cur.val);
                if (cur.left != null) q.add(cur.left);
                if (cur.right != null) q.add(cur.right);
            }
            if(k++%2==0) temp = reverseList(temp);
            list.add(temp);
        }


        return list;
    }
}

只需要在层序的基础上,加一个判断奇偶,然后在偶数层时把ArrayList反转就可以了

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务