Skip to content

Commit 58e319f

Browse files
authored
Create 40 Diameter of binary tree.cpp
1 parent 476ff4d commit 58e319f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
private:
14+
int res;
15+
public:
16+
int Solve(TreeNode* root) {
17+
if (root == NULL)
18+
return 0;
19+
20+
int l = Solve(root->left);
21+
int r = Solve(root->right);
22+
23+
int temp = 1 + max(l, r);
24+
int ans = max(temp, l + r + 1);
25+
res = max(res, ans);
26+
return temp;
27+
}
28+
int diameterOfBinaryTree(TreeNode* root) {
29+
if (root == NULL)
30+
return 0;
31+
32+
res = INT_MIN + 1;
33+
Solve(root);
34+
return res - 1;
35+
}
36+
};

0 commit comments

Comments
 (0)