题解 | #树查找# 小心数组越界问题。

树查找

https://www.nowcoder.com/practice/9a10d5e7d99c45e2a462644d46c428e4

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt(); // 树中节点的个数
            int[] nodes = new int[n];
            for (int i = 0; i < n; i++) {
                nodes[i] = sc.nextInt(); // 输入树中的节点值
            }
            int d = sc.nextInt(); // 深度
            printNodesAtDepth(nodes, d);
        }
        sc.close();
    }

    private static void printNodesAtDepth(int[] nodes, int d) {
        int start = (int) Math.pow(2,
                                   d - 1) - 1; // 计算深度为d的节点在数组中的起始位置
        int end = Math.min((int) Math.pow(2, d) - 2,
                           nodes.length - 1); // 计算深度为d的节点在数组中的结束位置
        if (start >= nodes.length) {
            System.out.println("EMPTY");
            return;
        }
        for (int i = start; i <= end; i++) {
            System.out.print(nodes[i]);
            if (i < end) {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}

全部评论

相关推荐

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