[英]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.