generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.cpp
66 lines (64 loc) · 1.99 KB
/
solution.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
struct Distance {
int val;
int rev;
};
class Solution {
public:
int amountOfTime(TreeNode* root, int start) {
const auto distance = largestDistance(root, start);
return std::max(distance.val, distance.rev);
}
Distance largestDistance(TreeNode* node, int start) {
if (node->val == start) {
if (node->left != nullptr) {
if (node->right != nullptr) {
const auto left = largestDistance(node->left, start);
const auto right = largestDistance(node->right, start);
return {
.val = std::max(left.val, right.val),
.rev = 0};
} else {
auto left = largestDistance(node->left, start);
left.rev = 0;
return left;
}
} else if (node->right != nullptr) {
auto right = largestDistance(node->right, start);
right.rev = 0;
return right;
} else {
return {.val = 0, .rev = 0};
}
} else {
if (node->left != nullptr) {
if (node->right != nullptr) {
const auto left = largestDistance(node->left, start);
const auto right = largestDistance(node->right, start);
if (left.rev >= 0) {
return {
.val = std::max(left.val, 1 + right.val + left.rev),
.rev = left.rev + 1};
} else if (right.rev >= 0) {
return {
.val = std::max(1 + left.val + right.rev, right.val),
.rev = right.rev + 1};
} else {
return {
.val = 1 + std::max(left.val, right.val),
.rev = -1};
}
} else {
auto left = largestDistance(node->left, start);
left.rev >= 0 ? ++left.rev : ++left.val;
return left;
}
} else if (node->right != nullptr) {
auto right = largestDistance(node->right, start);
right.rev >= 0 ? ++right.rev : ++right.val;
return right;
} else {
return {.val = 1, .rev = -1};
}
}
}
};