-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiameterBinaryTree.cpp
45 lines (35 loc) · 1.05 KB
/
diameterBinaryTree.cpp
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
//Geeks for Geeks question
class Solution {
private:
int height(struct Node* node){
//base case
if(node == NULL) {
return 0;
}
int left = height(node ->left);
int right = height(node->right);
int ans = max(left, right) + 1;
return ans;
}
public:
// Function to return the diameter of a Binary Tree.
pair<int,int> diameterFast(Node* root) {
//base case
if(root == NULL) {
pair<int,int> p = make_pair(0,0);
return p;
}
pair<int,int> left = diameterFast(root->left);
pair<int,int> right = diameterFast(root->right);
int op1 = left.first;
int op2 = right.first;
int op3 = left.second + right.second + 1;
pair<int,int> ans;
ans.first = max(op1, max(op2, op3));;
ans.second = max(left.second , right.second) + 1;
return ans;
}
int diameter(Node* root) {
return diameterFast(root).first;
}
};