このアルゴリズムは、一般的な二分木をレベルごとに出力するためのものです。
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();
}
}