Search code examples
javarecursionruntimebinary-tree

How to calculate the runtime of this function?


I am trying to calculate the runtime of a function I wrote in Javq, I wrote a function that calculates the sum of all the right children in a BT.

I used recursion in the function, and I don't really understand how to calculate the runtime in recursion non the less in a BT (just started studying the subject).

This is the code I wrote:

public int sumOfRightChildren(){
    return sumOfRightChildren(this.root);
}

private int sumOfRightChildren(Node root){
    if(root == null) //O(1)
        return 0;//O(1)
    int sum = 0;//O(1)
    if(root.right != null)//O(1)
        sum+=root.right.data;//O(1)
    sum += sumOfRightChildren(root.right); //worst case O(n) ?
    if(root.left != null)
    {
       sum += sumOfRightChildren(root.left);//worst case O(n)?
    }
    return  sum;
}

I tried writing down the runtimes I think it takes, but I don't think I am doing it right. If someone can help guide me I'd be very thankful.

I'm trying to calculate T(n).


Solution

  • Since you visit every node exactly once is easy to see the runtime cost is T(n) = n * K where n is the number of nodes in the Binary Tree and K is the expected function cost.

    If you want to explicitly consider the cost of certain operations you may not be able to calculate it exactly (without having an input example). For example, calculating the number of times sum+=... is executed is not possible because it depends on the particular tree.

    In this case the worst case is a full Binary Tree and, if it is n=1,2,... their depth:

    1. the complexity is O(2^n) (no matter the operations since all of them take O(1) as you have posted).
    2. the cost of sum+=root.right.data; is T(n) = 2^n - 1 (all internal nodes).
    3. the cost of sum+=... is T(n) = 3 * (2^n - 1) (twice for every internal node and one more for each node).
    4. ...

    (NOTE: the exact final expression may vary since your if(root.left != null) is not usefull and prefereable let that condition to the if(root == null))