File tree Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change
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
+ // printing the final value
60
+ cout<<" Diameter" <<final_diameter (root);
61
+ return 0 ;
62
+ }
63
+
64
+ /*
65
+ OUTPUT
66
+
67
+ 5
68
+ / \ the longest path is from the node conatining value '4' to node containing
69
+ 3 1 value '1'.
70
+ / \
71
+ 9 6
72
+
73
+ Diameter:4
74
+
75
+
76
+ */
You can’t perform that action at this time.
0 commit comments