#include <iostream>
using namespace std;
struct node
{
int data;
node * left;
node *right;
};
int height(node *t);
int max(int a ,int b)
{
if(a>b)
return a;
else return b;
}
int diameter(node *t)
{
if(t==NULL)return 0;
int ld=diameter(t->left);
int rd=diameter(t->right);
int lh=height(t->left);
int rh=height(t->right);
return max((lh+rh+1),max(lh,rh));
}
void create(node *&t,int a)
{
if(t==NULL)
{
t=new node;
t->data=a;
t->left=NULL;
t->right=NULL;
}
else if(a<t->data)
{
create(t->left,a);
}
else {
create(t->right,a);
}
}
void print(node *t)
{
if(t!=NULL)
{
print(t->left);
print(t->right);
cout<<t->data<<" ";
}
}
int height(node *t)
{
if(t==NULL)
return 0;
return 1+max(height(t->left),height(t->right));
}
int main()
{int k;
node *t;
t=NULL;
int a[]={10,6,4,7,14,12,16,-1};
int i=0;
while(a[i]!=-1)
{
create(t,a[i]);
i++;
}
print(t);
cout<<diameter(t);
return 0;
}
using namespace std;
struct node
{
int data;
node * left;
node *right;
};
int height(node *t);
int max(int a ,int b)
{
if(a>b)
return a;
else return b;
}
int diameter(node *t)
{
if(t==NULL)return 0;
int ld=diameter(t->left);
int rd=diameter(t->right);
int lh=height(t->left);
int rh=height(t->right);
return max((lh+rh+1),max(lh,rh));
}
void create(node *&t,int a)
{
if(t==NULL)
{
t=new node;
t->data=a;
t->left=NULL;
t->right=NULL;
}
else if(a<t->data)
{
create(t->left,a);
}
else {
create(t->right,a);
}
}
void print(node *t)
{
if(t!=NULL)
{
print(t->left);
print(t->right);
cout<<t->data<<" ";
}
}
int height(node *t)
{
if(t==NULL)
return 0;
return 1+max(height(t->left),height(t->right));
}
int main()
{int k;
node *t;
t=NULL;
int a[]={10,6,4,7,14,12,16,-1};
int i=0;
while(a[i]!=-1)
{
create(t,a[i]);
i++;
}
print(t);
cout<<diameter(t);
return 0;
}
No comments:
Post a Comment