题解 | #牛群Z字型排列#java 集合转数组无需再次遍历

牛群Z字型排列

https://www.nowcoder.com/practice/50ddaf50c6954600a9f1dbb099d6f388

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 root TreeNode类
     * @return int整型二维数组
     */
    public int[][] ZLevelOrder (TreeNode root) {
        if (root == null) return new int[0][];
        //层序遍历 一次放入一层的数据 再取出一层的数据
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        //int基本类型不能作为List的泛型 但是 int[] 是对象类型 可以作为泛型
        List<int[]> outList = new ArrayList<>();
        //根节点是从左到右
        boolean isLeftToRight = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            int[] arr = new int[size];
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (isLeftToRight) {
                    arr[i] = node.val;
                } else {
                    arr[size - i - 1] = node.val;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            isLeftToRight = !isLeftToRight;
            outList.add(arr);
        }
        return outList.toArray(new int[0][]);
    }
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

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