赞
踩
给定一棵包含 NN 个节点的完全二叉树,树上每个节点都有一个权值,按从 上到下、从左到右的顺序依次是 A_1, A_2, ··· A_NA1,A2,⋅⋅⋅AN,如下图所示:
现在小明要把相同深度的节点的权值加在一起,他想知道哪个深度的节点 权值之和最大?如果有多个深度的权值和同为最大,请你输出其中最小的深度。
注:根的深度是 1。
第一行包含一个整数 N(10的五次)。
第二行包含 N 个整数 A1,A2,⋅⋅⋅AN(−105≤Ai≤105)。
输出一个整数代表答案。
示例
输入
- 7
- 1 6 5 4 3 2 1
输出
2
要统计完全二叉树的某一层的最大和,由于完全二叉树对应于数组,所以按照2的幂次方 依次遍历数组即可,注意在遍历时,防止因为不是满二叉树而数组越界。
- import java.io.*;
-
- public class Main {
- public static void main(String[] args) throws NumberFormatException, IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- int n = Integer.parseInt(br.readLine());
- String[] split = br.readLine().split(" ");
- int []arr = new int[n];
- for(int i = 0; i < split.length; i++) {
- arr[i] = Integer.parseInt(split[i]);
- }
- int count = 0;//幂的次数
- int i = 0;//数组的索引
- int max = Integer.MIN_VALUE;//每一层的和
- boolean flag = true;
- int ans = 0;
- while(flag) {
- int tag = 0;//每层最多的节点数
- tag = (int)Math.pow(2, count++);
- int sum = 0;
- for(int j = 1;j <= tag; j++) {
- if(i >= n) {
- flag = false;
- break;
- }
- sum += arr[i++];
- }
- if(sum > max) {//最大的和
- max = sum;
- ans = count;
- }
- }
- System.out.println(ans);
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。