fork download
  1. #include <iostream>
  2. #include<stack>
  3. using namespace std;
  4. struct node
  5. {
  6. int data;
  7. struct node *left;
  8. struct node *right;
  9. };
  10. struct node* newNode(int data)
  11.  
  12. {
  13. struct node* node = (struct node*)
  14. malloc(sizeof(struct node));
  15. node->data = data;
  16. node->left = NULL;
  17. node->right = NULL;
  18.  
  19. return(node);
  20. }
  21. int max(int a,int b)
  22. {
  23. if(a>=b)return a;
  24. else return b;
  25. }
  26. int diameter(struct node *root,int *height)
  27. {
  28. if(!root){ *height=0; return 0;}
  29. int ls,rs,lh,rh;
  30. rs=0;ls=0;lh=0;rh=0;
  31. ls=diameter(root->left,&lh);
  32. rs=diameter(root->right,&rh);
  33. *height=max(lh,rh)+1;
  34. return max(lh+rh+1,max(ls,rs));
  35. }
  36. int main()
  37. {
  38. struct node *root = newNode(1);
  39. root->left = newNode(2);
  40. root->right = newNode(3);
  41. root->left->left = newNode(4);
  42. root->left->right = newNode(5);
  43. int height;
  44. printf("%d",diameter(root,&height));
  45.  
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
4