|
| 1 | +// The path which has the highest number of nodes is called the diameter of the binary tree. |
| 2 | +#include<bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | +class node |
| 5 | +{ |
| 6 | + public: |
| 7 | + int data; |
| 8 | + node *left; |
| 9 | + node *right; |
| 10 | +}; |
| 11 | +node* newnode(int data) |
| 12 | +{ |
| 13 | + node *newblock= new node(); |
| 14 | + newblock->left=NULL; |
| 15 | + newblock->right=NULL; |
| 16 | +} |
| 17 | +// calculating the height of the binary tree. |
| 18 | +int height (node *p) |
| 19 | +{ |
| 20 | + if(p==NULL) |
| 21 | + return 0; |
| 22 | + int left=height(p->left); |
| 23 | + int right=height(p->right); |
| 24 | + int h; |
| 25 | + if(left>right) |
| 26 | + { |
| 27 | + h=1+left; |
| 28 | + } |
| 29 | + else |
| 30 | + { |
| 31 | + h=1+right; |
| 32 | + } |
| 33 | + return h; |
| 34 | +} |
| 35 | +// calculating the diameter of the binary tree. |
| 36 | +int final_diameter(node *p) |
| 37 | +{ |
| 38 | + if(p==NULL) |
| 39 | + return 0; |
| 40 | + //value of the left node is passed to height function to calculate height of left sub tree. |
| 41 | + int left_height=height(p->left); |
| 42 | + //value of the right node is passed to height function to calculate height of right sub tree. |
| 43 | + int right_height=height(p->right); |
| 44 | + //calculating diameter of left subtree which does not include root node |
| 45 | + int left_diameter=final_diameter(p->left); |
| 46 | + //calculating diameter of right subtree which does not include root node |
| 47 | + int right_diameter=final_diameter(p->right); |
| 48 | + int final=max(left_height+right_height+1 , max(left_diameter,right_diameter)); |
| 49 | + return final; |
| 50 | +} |
| 51 | +int main() |
| 52 | +{ |
| 53 | + // formation of a binary tree |
| 54 | + node * root=newnode(5); |
| 55 | + root->left=newnode(3); |
| 56 | + root->left->left=newnode(9); |
| 57 | + root->right=newnode(1); |
| 58 | + root->left->right=newnode(6); |
| 59 | + root->left->right->left=newnode(7); |
| 60 | + // printing the final value |
| 61 | + cout<<"Diameter:"<<final_diameter(root); |
| 62 | + return 0; |
| 63 | +} |
| 64 | + |
| 65 | +/* |
| 66 | + OUTPUT |
| 67 | +
|
| 68 | + 5 |
| 69 | + / \ |
| 70 | + 3 1 |
| 71 | + / \ |
| 72 | + 9 6 |
| 73 | + / |
| 74 | + 7 |
| 75 | + |
| 76 | + Diameter:5 |
| 77 | + |
| 78 | + the longest path is from the node conatining value '7' |
| 79 | + to node containing value '1'. |
| 80 | + |
| 81 | +
|
| 82 | +*/ |
0 commit comments