543. 二叉树的直径
为保证权益,题目请参考 543. 二叉树的直径(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <limits.h>
#include <algorithm>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int ans;
int diameterOfBinaryTree(TreeNode *root)
{
ans = 0;
dfs(root);
return ans;
}
int dfs(TreeNode *root)
{
if (root)
{
int l = dfs(root->left);
int r = dfs(root->right);
ans = max(ans, l + r);
return max(l, r) + 1;
}
else
{
return 0;
}
return -1;
}
};
int main()
{
return 0;
}
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
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