-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0543_diameterOfBinaryTree.cc
66 lines (58 loc) · 1.34 KB
/
Problem_0543_diameterOfBinaryTree.cc
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
#include "UnitTest.h"
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
// 树型dp
class Solution
{
private:
class Info
{
public:
int maxDistance;
int height;
Info(int m, int h)
{
maxDistance = m;
height = h;
}
};
public:
int diameterOfBinaryTree(TreeNode* root) { return f(root).maxDistance; }
Info f(TreeNode* x)
{
if (x == nullptr)
{
return Info(0, 0);
}
Info left = f(x->left);
Info right = f(x->right);
int maxDistance =
std::max(std::max(left.maxDistance, right.maxDistance), left.height + right.height);
int height = std::max(left.height, right.height) + 1;
return Info(maxDistance, height);
}
};
void testDiameterOfBinaryTree()
{
Solution s;
TreeNode* x5 = new TreeNode(5, nullptr, nullptr);
TreeNode* x4 = new TreeNode(4, nullptr, nullptr);
TreeNode* x3 = new TreeNode(3, nullptr, nullptr);
TreeNode* x2 = new TreeNode(2, x4, x5);
TreeNode* x1 = new TreeNode(1, x2, x3);
EXPECT_EQ_INT(3, s.diameterOfBinaryTree(x1));
EXPECT_SUMMARY;
}
int main()
{
testDiameterOfBinaryTree();
return 0;
}