该算法用于逐级打印常见的二叉树。
和 的时间复杂度和空间复杂度是printSpecificLevel_BT()
多少printBT_LBL()
?
我认为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();
}
}