Diameter Of tree

i am getting different diameters from the code .
please Check-

hey @darkthunderassassin_818a6616c3c74f13
you have written Pair left=Fastdiameter(root->right); in fastdiameter() function it should be Pair left=Fastdiameter(root->left);

corrected code is
#include

#include

#include

#include

using namespace std;

class node{

public:

int data;

node *left;

node *right;

node(int x){

    data=x;

    left=NULL;

    right=NULL;

}

node(){

     data=0;

    left=NULL;

    right=NULL;

}

};

node *buildtree(){

int d;

cin>>d;

 if(d==-1){

     return NULL;

 }

 node*root=new node(d);

 root->left=buildtree();

 root->right=buildtree();

 return root;

}

void print(node*root){

if(root== NULL){

    return;

}

cout<<root->data<<" "; //preorder

print(root->left);

print(root->right);

}

int count(node*root){

if(root==NULL){

  return 0;

}

return 1+count(root->left)+count(root->right);

}

int height(node*root){

if(root==NULL){return 0;}

int ls=height(root->left);

int rs=height(root->right);

 return max(ls,rs)+1;

}

class Pair{

public:

int height;

int diameter;

};

Pair Fastdiameter(node*root){

Pair p;

if(root==NULL){

    p.diameter=p.height=0;

    return p;

}

//otherwise

//call left subtree and right subtree

Pair left=Fastdiameter(root->left);

Pair right=Fastdiameter(root->right);

p.height=max(left.height,right.height)+1;

p.diameter=max(left.height+right.height, max(left.diameter,right.diameter));

return p;

}

int diameterT(node*root){

if(root==NULL){

    return 0;

}

int h1=height(root->left);

int h2=height(root->right);

int op1=h1+h2;

int op2=diameterT(root->left);

int op3=diameterT(root->right);

return max(op1,max(op2,op3));

}

int main()

{

node* root=buildtree();

print(root);

//8 10 1 -1 -1 6 9 -1 -1 7-1-1 3 -1 14 13 -1 -1-1

//8 10 1 6 9 7 3 14 13

cout<<endl;

           

  cout<<diameterT(root)<<endl; //6

  Pair p=Fastdiameter(root);

  cout<<"height-"<<p.height<<" diameter-"<<p.diameter<<endl;

    

return 0;

}

hope it is clear now :wink:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.