簡體   English   中英

此函數的時間和空間復雜性逐級打印二叉樹

[英]Time and space complexity of this function to print binary tree level by level

該算法用於逐級打印公共二叉樹。

printSpecificLevel_BT()printBT_LBL()的時間復雜度和空間復雜度是printSpecificLevel_BT()

我認為printSpecificLevel_BT的時間復雜度是O(lg N) ,空間復雜度是O(lg N)
我認為printBT_LBL()的時間復雜度是O((lgN)^2) ,空間復雜度是O((lgN)^2)

這個對嗎?

// Print the specific level of a binary tree.
public static void printSpecificLevel_BT (Node root, int level) {
    if (root == null) return;
    if (level == 0) System.out.print(String.format("%-6d", root.data)); // Base case.
    // Do recrusion.
    printSpecificLevel_BT(root.leftCh, level - 1);
    printSpecificLevel_BT(root.rightCh, level - 1);
}

// Get the height of a binary tree.
public static int getHeight_BT (Node root) {
    if (root == null || (root.leftCh == null && root.rightCh == null)) return 0; // Base case.
    return 1 + Math.max (getHeight_BT(root.leftCh), getHeight_BT(root.rightCh));
}

// Print a binary tree level by level.
public static void printBT_LBL (Node root) {
    // Get the height of this binary tree.
    int height = getHeight_BT(root);
    for (int i = 0; i <= height; i ++) {
        printSpecificLevel_BT(root, i);
        System.out.println();
    }
}

printSpecificLevel_BTO(n)因為它查看樹中的每個節點。 但是,只需更改(在level == 0時返回),就可以使其為O(min(n, 2^level))

getHeightO(n)因為它查看樹中的每個節點。 printBT_LBL調用getHeight一次和printSpecificLevel_BT height時間,因此其復雜度為O(n + n*height) = O(n*height)

每個空間復雜度都是O(height)因為它一直遞歸到樹的底部。 你不能說O(log n)因為樹不一定是平衡的(除非它是)。

對於printSpecificLevel_BT()你有:

在此輸入圖像描述

對於printBT_LBL()你有:

在此輸入圖像描述

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM