-3
#include<stdio.h>
#include<malloc.h>

struct node
{
    int data;
    struct node* left;
    struct node* right;
};
struct node* newNode(int data)
{
    struct node* node=(struct node*)malloc(sizeof(struct node));
    node->data=data;
    node->left=NULL;
    node->right=NULL;

    return (node);
};

int height(struct node* root)
{
    static int lheight,rheight;
    if(root==NULL)
        return;
    else
    {
        lheight=height(root->left)+1;
        rheight=height(root->right)+1;
        if(lheight>rheight)
            return lheight;
        else
            return rheight;
    }

}

int main()
    {
          struct node* root=newNode(1);
          root->left=newNode(2);
          root->right       = newNode(3);
          root->left->left  = newNode(4);
          root->left->right = newNode(5);
          printf("%d",height(root));
          return 0;
    }

This program gives two different result. One is 2 for the above program where I use static and 3 if static is not used. Please explain the reason for the change in output using static.

1 Answers1

0

When you declare a local variable static, there's only one copy of that variable, not a separate copy for each call to the function. So when you call height() recursively, it overwrites the variables that are in use in the calling function.

Here's what's happening. First the function does:

lheight = height(root->left)+1;

This sets lheight to the height of the left branch of the current node + 1. Then you call:

rheight = height(root->right)+1;

Inside the recursive call to height, it again does:

lheight = height(root->left)+1;

So now lheight no longer contains the height of the parent's left branch, it contains the height of the right child's left branch + 1.

If you don't use static, each recursive level has its own variables, they aren't overwritten when you make the recursive calls.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I understand that. But why here two different outputs? – rohitjoins May 16 '14 at 22:55
  • Step through the function, either with a debugger or by writing the variables on a piece of paper, and see what happens. – Barmar May 16 '14 at 22:56
  • But there are two different static variables one is lheight and the other is rheight. – rohitjoins May 16 '14 at 23:12
  • But you're updating both variables during each recursive call. So after you set `lheight`, you then call `height` again on the right branch, and it overwrites `lheight`. – Barmar May 16 '14 at 23:14