题解 | #牛群Z字型排列#

牛群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) {
        // write code here
        if (root == null) {
            return new int[][] {};
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int h = 0;
        List<List<Integer>> matrix = new ArrayList<>();
        while (!queue.isEmpty()) {
            int len = queue.size();
            LinkedList<Integer> row = new LinkedList<>();
            h ++;
            for (int i = 0; i < len; i ++) {
                TreeNode node = queue.poll();
                if (h % 2 == 0) {
                    row.addFirst(node.val);
                } else {
                    row.addLast(node.val);
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            matrix.add(row);
        }
        return matrix.stream()
               .map(a ->a.stream().mapToInt(Integer::intValue).toArray())
               .toArray(int[][]::new);
    }
}

全部评论

相关推荐

__Offer__:认识的室友啥也不回细节,线下面联想大模型一次通关我给我干不回了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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