Sunday, April 15, 2012

Program 23RD in C++ VERSION 2


PROBLEM STATEMENT :

What is the diameter of a tree?

SOLUTION :

#include <iostream.h>
#include <cstdio>

using namespace std;

int flag = 1;

struct node
{
int data;
node *left;
node *right;
};

node* node(int n)
{

struct node* m = (struct node*)malloc(sizeof(struct node));

m->data=n;
m->left=NULL;
m->right=NULL;

return m;
}

int max(int a, int b)
{

return a>b?a:b;

}

int diameter(struct node* n, int* height)
{

int lh=0;
int rh=0;
int ld=0;
int rd=0;

if(n == 0)
{
*height=0;
return 0;
}

if(n->left == 0 && flag == 1)
{
n=n->right;
return diameter(n,height);
}
else if (n->right == 0 && flag == 1)
{
n=n->left;
return diameter(n,height);
}
else
{
flag=0;
}

ld = diameter (n->left,&lh);
rd = diameter (n->right,&rh);

*height=max(lh,rh)+1;

return (max(lh+rh+1,max(ld,rd)));
}

int main()
{

struct node* root = node(0);
root->right=node(1);
root->right->left=node(7);
root->right->right=node(2);
root->right->right->right=node(3);
root->right->right->right->left=node(4);
root->right->right->right->right=node(5);

int height;

cout<<diameter(root,&height);

}

No comments:

Post a Comment