Skip to content

Commit 0349792

Browse files
authored
Create Diameter_of_tree.cpp
1 parent 2baeb7e commit 0349792

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Trees/Diameter_of_tree.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
/* Tree node structure used in the program */
5+
struct Node
6+
{
7+
int data;
8+
Node *left, *right;
9+
};
10+
11+
/* Function to find height of a tree */
12+
int height(Node *root, int &ans)
13+
{
14+
if (root == NULL)
15+
return 0;
16+
17+
int left_height = height(root->left, ans);
18+
19+
int right_height = height(root->right, ans);
20+
21+
// update the answer, because diameter of a
22+
// tree is nothing but maximum value of
23+
// (left_height + right_height + 1) for each node
24+
ans = max(ans, 1 + left_height + right_height);
25+
26+
return 1 + max(left_height, right_height);
27+
}
28+
29+
/* Computes the diameter of binary tree with given root. */
30+
int diameter(Node *root)
31+
{
32+
if (root == NULL)
33+
return 0;
34+
int ans = INT_MIN; // This will store the final answer
35+
height(root, ans);
36+
return ans;
37+
}
38+
39+
struct Node *newNode(int data)
40+
{
41+
struct Node *node = new Node;
42+
node->data = data;
43+
node->left = node->right = NULL;
44+
45+
return (node);
46+
}
47+
48+
// Driver code
49+
int main()
50+
{
51+
struct Node *root = newNode(1);
52+
root->left = newNode(2);
53+
root->right = newNode(3);
54+
root->left->left = newNode(4);
55+
root->left->right = newNode(5);
56+
57+
printf("Diameter is %d\n", diameter(root));
58+
59+
return 0;
60+
}

0 commit comments

Comments
 (0)