[英]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_BT
是O(n)
因為它查看樹中的每個節點。 但是,只需更改(在level == 0
時返回),就可以使其為O(min(n, 2^level))
。
getHeight
是O(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.