Venkatesh Marepalli
Venkatesh Marepalli

Reputation: 606

Recursion : How do I return value-1 from recursive function

I wrote a method to return the height of a Binary Search Tree.

Now I am trying to return height - 1 from the recursive method. I am doing this by adding extra if conditions.

Is there a better way to return the value - 1 from the recursive function?

static int height(Node root) {
    if (root == null) {       
        return 0;
    }

    if (root.left == null && root.right==null) {      
        return 1;            
    } else
        // I want to return height - 1.
        // For example if max height is 10, I wanted to return 9.
        return (1 + Math.max(height(root.left), height(root.right));   
    }
}

Upvotes: 0

Views: 126

Answers (1)

Henry
Henry

Reputation: 43758

In your base cases return -1 and 0 respectively:

static int height(Node root) {
    if(root == null)       
        return -1;
    if(root.left == null && root.right==null)      
        return 0;            
    else
        return 1+ Math.max(height(root.left),
                   height(root.right));   
}

Update to comply with requirement mentioned in comment: "What if I wanted to return 0 for null node, 1 for single node and if height-1 for all other."

static int funny_height(Node root) {
    int h = height(node);
    return h <= 0 ? h + 1 : h;
}

Upvotes: 3

Related Questions