简体   繁体   English

此函数的时间和空间复杂性逐级打印二叉树

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

This algorithm is for printing a common binary tree level by level. 该算法用于逐级打印公共二叉树。

What is the time complexity and space complexity of printSpecificLevel_BT() and printBT_LBL() ? printSpecificLevel_BT()printBT_LBL()的时间复杂度和空间复杂度是printSpecificLevel_BT()

I think printSpecificLevel_BT 's time complexity is O(lg N) , and space complexity is O(lg N) . 我认为printSpecificLevel_BT的时间复杂度是O(lg N) ,空间复杂度是O(lg N)
I think printBT_LBL() 's time complexity is O((lgN)^2) , and the space complexity is O((lgN)^2) . 我认为printBT_LBL()的时间复杂度是O((lgN)^2) ,空间复杂度是O((lgN)^2)

Is this correct? 这个对吗?

// 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 is O(n) since it looks at every node in the tree. printSpecificLevel_BTO(n)因为它查看树中的每个节点。 However, with a simply change (returning when level == 0 ), you can make it O(min(n, 2^level)) . 但是,只需更改(在level == 0时返回),就可以使其为O(min(n, 2^level))

getHeight is O(n) since it looks at every node in the tree. getHeightO(n)因为它查看树中的每个节点。 printBT_LBL calls getHeight once and printSpecificLevel_BT height times, so its complexity is O(n + n*height) = O(n*height) . printBT_LBL调用getHeight一次和printSpecificLevel_BT height时间,因此其复杂度为O(n + n*height) = O(n*height)

The space complexity of each is O(height) since it recurses all the way to the bottom of the tree. 每个空间复杂度都是O(height)因为它一直递归到树的底部。 You can't say the O(log n) since the tree isn't necessarily balanced (unless it is). 你不能说O(log n)因为树不一定是平衡的(除非它是)。

For printSpecificLevel_BT() you have: 对于printSpecificLevel_BT()你有:

在此输入图像描述

For printBT_LBL() you have: 对于printBT_LBL()你有:

在此输入图像描述

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM