-
Notifications
You must be signed in to change notification settings - Fork 22
/
diameter of binary tree
70 lines (57 loc) · 1.63 KB
/
diameter of binary tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Given a Binary Tree, find diameter of it.
+The diameter of a tree is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees
each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree
of length nine, but no path longer than nine nodes).
Input Format:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains two lines of input.
The first line contains number of edges. The second line contains the relation between nodes.
Output Format:
For each testcase, in a new line, print the diameter.
Your Task:
You need to complete the function diameter() that takes node as parameter and returns the diameter.
Constraints:
1 <= T <= 30
1 <= Number of nodes <= 100
1 <= Data of a node <= 1000
Example:
Input:
2
2
1 2 L 1 3 R
4
10 20 L 10 30 R 20 40 L 20 60 R
Output:
3
4
Explanation:
Testcase1: The tree is
1
/ \
2 3
The diameter is of 3 length.
Testcase2: The tree is
10
/ \
20 30
/ \
40 60
The diameter is of 4 length.
*/
int height(Node *r){
if(r==NULL) return 0;
else{
int l=height(r->left);
int r1=height(r->right);
if(l>r1) return l+1;
else return r1+1;
}
}
int diameter(Node* node)
{
if(node==NULL) return 0;
int k= height(node->left) + height(node->right)+1;
int l=diameter(node->left);
int r=diameter(node->right);
return max(k , max(r,l));
}