gpt4 book ai didi

Java : How to print heap stored as array,逐级

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:33 25 4
gpt4 key购买 nike

我有一个代表最大堆的数组。例如

84 81 41 79 17 38 33 15 61 6

所以根是最大值。索引 i 处的每个中间层节点最多可以有两个 child 。它们将位于 2*i+1 和 2*i+2。

如何逐层打印这个堆?喜欢

                             84(0)

81(1) 41(2)

79(3) 17(4) 38(5) 33(6)

15(7) 61(8) 6(9)

为了清楚起见,数组中每个元素的索引都显示在括号中。我不必打印索引。我认为这类似于按级别顺序打印 BST,但在这里,堆存储在数组中而不是列表中,这使得它有点棘手!

最佳答案

试试这个代码:

public class NewClass56 {
public static void main(String args[]){

int a[] = new int[] {84 ,81 ,41 ,79 ,17 ,38 ,33 ,15 ,61 ,6};

for(int i=0;i<10;i++){
for(int j=0;j<Math.pow(2,i)&&j+Math.pow(2,i)<10;j++){
System.out.print(a[j+(int)Math.pow(2,i)-1]+" ");

}
System.out.println();
}



}
}

如果您有 n 个数字,则将 10 替换为 n

你想要空格然后试试这个代码:

public class NewClass56 {
public static void main(String args[]){

int a[] = new int[] {84 ,81 ,41 ,79 ,17 ,38 ,33 ,15 ,61 ,6};
StringBuilder sb = new StringBuilder();
int max=0;
for(int i=0;i<10;i++){
for(int j=0;j<Math.pow(2,i)&&j+Math.pow(2,i)<10;j++){

if(j>max){
max=j;
}
}

}

for(int i=0;i<10;i++){
for(int j=0;j<Math.pow(2,i)&&j+Math.pow(2,i)<10;j++){

for(int k=0;(k<max/((int)Math.pow(2, i)));k++){
sb.append(" ");
}
sb.append(a[j+(int)Math.pow(2,i)-1]+" ");

}
sb.append("\n");

}



System.out.println(sb.toString());

}
}

关于Java : How to print heap stored as array,逐级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36385868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com