在 Console 中輸出樹形結構

前言

console代碼中輸出一個樹形的結構,這個在寫堆排序的時候,直接打印樹形結構debug,很爽,實際效果很水,如下圖

在這裏插入圖片描述

代碼

int[] arr = new int[]{2, 7, 4, 20, 11, 16, 8, 13, 17, 19, 3, 56, 68, 29, 18};
int len = arr.length;
int ceng = (int) Math.sqrt(len) + 1;
for (int i = 0; i <= ceng; i++) {
    int frontT = (int) Math.pow(2, ceng - i - 1);
    for (int t = 0; t < frontT; t++)
        System.out.print("\t");

    int cStart = (int) Math.pow(2, i) - 1;
    int cNum = (int) Math.pow(2, i);
    for (int j = 0; j < cNum; j++) {
        if (cStart + j > len - 1)
            continue;
        System.out.print(arr[cStart + j]);

        int middleT = (int) Math.pow(2, ceng - i);
        for (int t = 0; t < middleT; t++)
            System.out.print("\t");
    }
    System.out.println();
    System.out.println();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章