Question

I'm having trouble understanding a Big O problem.

The Problem

public boolean isHB(TreeNode root){
    if (root==null)
        return tree;
    int heightL = height(root.left);
    int heightR = height(root.right);
    boolean leftHB = isHB(root.left);
    boolean rightHB = isHB(root.right);
    if (Math.abs(heightL-heightR)>1)
        return false;
    return leftHB && rightHB;
}

1/ Assume the tree is height balanced. Find the Big O where n is the number of nodes in the tree.

2/ Do not assume the tree is height balanced. Find the Big O where n is the number of nodes in the tree.

What I don't understand

1/ The solution is: 2T(2/n) + O(n) = O(n log(n)). I understand where the 2T(2/n) is from but I can't figure out where the O(n) is from.

2/ The solution is: T(n-1) + O(n) = O(n^2). In this case since the tree isn't balanced, I understand the T(n-1) but I still can't figure out where the O(n) comes from.

Was it helpful?

Solution

finding height of a tree has complexity O(n). So the extra part is the complexity of finding the height.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top