Skip to content

Commit afc84ea

Browse files
authored
Create main.cpp
1 parent bbc60df commit afc84ea

File tree

1 file changed

+28
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/06 - Diameter of a Binary Tree

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
pair<int, int> diameterFast(Node* root){
4+
// base case
5+
if(root == NULL){
6+
pair<int, int> p = make_pair(0, 0);
7+
return p;
8+
};
9+
10+
pair<int, int> left = diameterFast(root -> left);
11+
pair<int, int> right = diameterFast(root -> right);
12+
13+
int op1 = left.first;
14+
int op2 = right.first;
15+
int op3 = left.second + right.second + 1;
16+
17+
18+
pair<int, int> ans;
19+
ans.first = max(op1, max(op2, op3));
20+
ans.second = max(left.second, right.second) + 1;
21+
22+
return ans;
23+
}
24+
25+
int diameter(Node* root) {
26+
return diameterFast(root).first;
27+
}
28+
};

0 commit comments

Comments
 (0)