Java : 如何逐层打印存储为数组的堆

Java : How to print heap stored as array, level by level

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

84 81 41 79 17 38 33 15 61 6

所以根是最大值。索引 i 处的每个中间层节点最多可以有两个 children。它们将位于 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,但在这里,堆存储在数组中而不是列表中,这使得它有点棘手!

如果你想将它存储在一个列表列表中(级别顺序),只需为 2 的每个幂拆分一次,例如 1,2,4,8,16 ..

    private ArrayList<ArrayList<Integer>> heapParse(int[] arr) {

    ArrayList<ArrayList<Integer>> heap = new ArrayList<ArrayList<Integer>>();
    int j=-1;
    for (int i=0; i< arr.length;i++){
        if(isPowerOfTwo(i+1)){                
            heap.add(new ArrayList<>());
            j++;
        }
        heap.get(j).add(arr[i]);
    }       
    return heap;
    }

    private boolean isPowerOfTwo(int i){
       return (i&(i-1))==0;
    }

试试这个代码:

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());

}
}

分而治之。创建子树的行列表,连接行并为子树的根节点添加 String。还要确保线条具有相同的长度并且都居中:

static String pad(String s, int lengthRigth, int length) {
    StringBuilder sb = new StringBuilder();

    for (int i = length - lengthRigth - s.length(); i > 0; i--) {
        sb.append(' ');
    }

    sb.append(s);

    for (int i = 0; i < lengthRigth; i++) {
        sb.append(' ');
    }

    return sb.toString();
}

static StringBuilder withSpacesAppended(String s, int spaceCount) {
    StringBuilder sb = new StringBuilder(s.length()+spaceCount).append(s);
    for (int i = 0; i < spaceCount; i++) {
        sb.append(' ');
    }
    return sb;
}

static void joinLists(List<String> list1, List<String> list2) {
    int i;
    final int size = list2.size();
    for (i = 0; i < size; i++) {
        list1.set(i, withSpacesAppended(list1.get(i), 2).append(list2.get(i)).toString());
    }
}

static List<String> createTreeStrings(int index, int[] array) {
    int child1 = 2 * index + 1;
    int child2 = 2 * index + 2;
    if (child1 >= array.length) {
        return new ArrayList<>(Collections.singletonList(toText(index, array)));
    } else {
        List<String> childList1 = createTreeStrings(child1, array);
        if (child2 < array.length) {
            joinLists(childList1, createTreeStrings(child2, array));
        }
        String text = toText(index, array);
        int currentLength = childList1.get(0).length();

        if (currentLength >= text.length()) {
            text = pad(text, (currentLength - text.length()) / 2, currentLength);
        } else {
            for (int i = 0, size = childList1.size(); i < size; i++) {
                childList1.set(i, pad(childList1.get(i), (currentLength - text.length()) / 2, currentLength));
            }
        }

        childList1.add(0, text);
        return childList1;
    }
}

static String toText(int index, int[] array) {
    return Integer.toString(array[index]) + '(' + index + ')';
}

使用示例:

createTreeStrings(0, new int[]{84, 81, 41, 79, 17, 38, 33, 15, 61, 6}).forEach(System.out::println);
createTreeStrings(0, new int[]{Integer.MAX_VALUE, 6}).forEach(System.out::println);

还有另一种打印堆的方法。假设您有具有以下索引的结构(索引 0 是保护者,等于 Integer.MIN_VALUE,此处未显示):

          1
      /      \
    2          3
  /    \       / \
 4     5      6   7
/ \    /\     /\  /\
8 9  10 11 12 13 14 15 

它由数字数组表示。你在这里看到了什么?对,1, 3, 7, 15。如果将它增加 1,它将是 2, 4, 8, 16.

这些数字是多少?只是2^level。其中 level 是从 1 到 4 的级别。

我们如何计算这个级别?它是以 2 为底的指数的对数。

这是实现此方法的代码(参见 dump 函数):

package org.solutions;
import java.util.ArrayList;
import java.util.Arrays;

class Heap {
    public ArrayList<Integer> arr;
    public Heap() {
        this.arr = new ArrayList<>();
        arr.add(Integer.MIN_VALUE); // add guardian
    }

    public void add(int x) {
        int i = arr.size();
        arr.add(x);
        while(arr.get(i) < arr.get(i / 2)) {
            swap(i, i/2);
            i = i / 2;
        }
    }

    private void swap(int i, int j) {
        int tmp = arr.get(i);
        arr.set(i, arr.get(j));
        arr.set(j, tmp);
    }

    public void dump() {
        int height = log2(arr.size()) + 1;

        for (int i = 1, len = arr.size(); i < len; i++) {
            int x = arr.get(i);
            int level = log2(i) + 1;
            int spaces = (height - level + 1) * 2;

            System.out.print(stringOfSize(spaces, ' '));
            System.out.print(x);

            if((int)Math.pow(2, level) - 1 == i) System.out.println();
        }
    }

    private String stringOfSize(int size, char ch) {
        char[] a = new char[size];
        Arrays.fill(a, ch);
        return new String(a);
    }

    // log with base 2
    private int log2(int x) {
        return (int)(Math.log(x) / Math.log(2)); // = log(x) with base 10 / log(2) with base 10
    }
}

public class Main {

    public static void main(String[] args) {
        Heap heap = new Heap();
        heap.add(30);
        heap.add(2);
        heap.add(15);
        heap.add(10);
        heap.add(31);
        heap.dump();
    }
}

已接受的答案创建了许多新行,并在显示时忽略了最后一个元素。因此分享优化代码,

public void display() {
        // n is number of elements in the heap
        // It can be further optimised by calculating height of the heap
        // and looping i only till height of the tree
        for (int i = 0; i <= n / 2; i++) {
            for (int j = 0; j < Math.pow(2, i) && j + Math.pow(2, i) <= n; j++) { // Each row has 2^n nodes
                System.out.print(heap[j + (int) Math.pow(2, i) - 1] + " ");
            }
            System.out.println();
        }
    }

现有的解决方案对我不起作用,所以这里有一种稍微不同的方法,我认为它也更易于阅读。此外,这不使用任何外部库。请注意,这假定数组的第一个位置为空,因为通常 array-based 堆会跳过数组 [0]。这将根据输入大小自动确定级别数,输入大小应该是堆中的节点数。它会在每个空的地方添加 --(例如,如果你有一个 13 节点的堆,最后两个节点将显示为空)。

private void printHeap(int[] heap, size) {
    int maxDepth = (int) (Math.log(size) / Math.log(2));  // log base 2 of n

    StringBuilder hs = new StringBuilder();  // heap string builder
    for(int d = maxDepth; d >= 0; d--) {  // number of layers, we build this backwards
        int layerLength = (int) Math.pow(2, d);  // numbers per layer

        StringBuilder line = new StringBuilder();  // line string builder
        for(int i = layerLength; i < (int) Math.pow(2, d + 1); i++) {
            // before spaces only on not-last layer
            if(d != maxDepth) {
                line.append(" ".repeat((int) Math.pow(2, maxDepth - d)));
            }
            // extra spaces for long lines
            int loops = maxDepth - d;
            if(loops >= 2) {
                loops -= 2;
                while(loops >= 0) {
                    line.append(" ".repeat((int) Math.pow(2, loops)));
                    loops--;
                }
            }

            // add in the number
            if(i <= size) {
                line.append(String.format("%-2s", heap[i]));  // add leading zeros
            } else {
                line.append("--");
            }

            line.append(" ".repeat((int) Math.pow(2, maxDepth - d)));  // after spaces
            // extra spaces for long lines
            loops = maxDepth - d;
            if(loops >= 2) {
                loops -= 2;
                while(loops >= 0) {
                    line.append(" ".repeat((int) Math.pow(2, loops)));
                    loops--;
                }
            }
        }
        hs.insert(0, line.toString() + "\n");  // prepend line
    }
    System.out.println(hs.toString());
}

示例输入:

int[] heap = new int[]{0, 84, 81, 41, 79, 17, 38, 33, 15, 61, 6};
int size = heap.length-1 = 10

示例输出:

           84           
     81          41     
  79    17    38    33  
15 61 6  -- -- -- -- -- 

如有必要,您应该能够相当轻松地将其更改为用作 toString 方法。如果您想使用 3 位数字,则必须修改间距,如果有人要求,我可以使用修改后的代码进行编辑。

  • 以下算法将按定义的网格长度打印值。
  • 例如,最大元素等于 100,表示每个数字位于长度 == 3 的占位符中。如果最大长度为偶数,例如:4。那么占位符值将为 5。始终为中心赔率对齐方式。
  • 结果:
    [placeholder == 3] && [maxWidthLine == 31]
                  100               // [rear == 14] && [between == 29 -> Not Use]
          15-             17-       // [rear == 6] && [between == 13]
      -9-     -6-     13-     10-   // [rear == 2] && [between == 5]
    -4- -8- -3- -1- -5- --- --- --- // [rear == 0] && [between == 1]
  • 结果:
    [placeholder == 5] && [maxWidthLine == 5 * 2^3 + 2 ^ 3 - 1 == 47]
    
                     1000-                      // [Level == 0]
         -17--                   -13--          // [Level == 1]
   --9--       -15--       --5--       -10--    // [Level == 2]
--4-- --8-- --3-- --6-- --1-- ----- ----- ----- // [Level == 3]

  • TypeScript 源代码:
/** @example
 ** > format(10, 3) -> "10-"
 ** > format(10, 4) -> "-10-"
 ** > format(100, 3) -> "100"
 ** > format(100, 4) -> "100-"
 **/
const format = <T extends string | number>(value: T, placeholder: number): string => {
    if (!value && value !== 0) {
        return "-".repeat(placeholder);
    }
    const number = Number.call(null, value).toString();
    const size = number.length;
    if (size > placeholder) {
        throw new EvalError(">>> Place-Holder is smaller than Number Length <<<");
    }
    const pads = (placeholder - size) >> 1;
    return "-".repeat(pads) + number + "-".repeat(placeholder - size - pads);
};

public print(): void {
    const size = this.heap.length;
    const maxDigit = Math.max(...this.heap as Array<number>);
    /** Place holder must be odds [1, 3, 5, 7, 9, 11, ...] ~!*/
    const placeholder = (Number.call(null, maxDigit).toString().length & ~1) + 1;
    /** Max Depth of Binary Search Tree from [0] to [N] ~!*/
    const maxDepth = Math.floor(Math.log(size) / Math.log(2)); // Min Depth = 0; [Root Level]
    /** Total Spaces of Line == <The Amount of placeholders> && <The Amount of Space-1 between Placeholders> ~!*/
    const totalLineSpaces = placeholder * (2 ** maxDepth) + (2 ** maxDepth - 1);
    /** Calculate the spaces need to pad to the Rear-Side and Between each Placeholders ~!*/
    const calculateSpace = (level: number): [number, number] => {
        /** @equation: ${TotalSpaces} - ${placeholder} * (2 ^ level) == 2x + (2 ^ level - 1)(2x + 1) ~!*/
        /** @constraint: ${BetweenSpaces} == (2x + 1) <- Space between each placeholders ~!*/
        const rear = (totalLineSpaces - (placeholder + 1) * (2 ** level) + 1) / Math.pow(2, level + 1);
        return [rear, 2 * rear + 1];
    };
    console.log("------------------------------------------");
    console.log(">>> Array representation of Heap Array <<<");
    console.log("------------------------------------------\n");

    let str = ''; /** Heap string builder ~!*/
    for (let level = 0; level <= maxDepth; level++) {
        const [rear, middle] = calculateSpace(level);
        if (level === 0) {
            str += " ".repeat(rear) + this.format(this.heap[0], placeholder) + " ".repeat(rear) + "\n";
            continue;
        }
        const elements: Array<string> = [];
        /** @description: Looping through each Tree-Layer. Ranged from [2^level - 1] to [2^(level+1) - 2] ~!*/
        for (let i = Math.pow(2, level) - 1; i <= Math.pow(2, level + 1) - 2; i++) {
            elements.push(this.format(this.heap[i], placeholder));
        }
        str += " ".repeat(rear) + elements.join(" ".repeat(middle)) + " ".repeat(rear) + "\n";
    }
    str += "\n" + "------------------------------------------";
    return console.log(str);
};