mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
43 lines
1.1 KiB
C++
43 lines
1.1 KiB
C++
/**
|
|
* Definition for a binary tree node.
|
|
* 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) {}
|
|
* };
|
|
*/
|
|
class Solution {
|
|
int dfs(TreeNode *root, int start, int &time) {
|
|
if (root == nullptr) {
|
|
return 0;
|
|
}
|
|
|
|
int left = dfs(root->left, start, time);
|
|
int right = dfs(root->right, start, time);
|
|
|
|
if (root->val == start) {
|
|
time = std::max(left, right);
|
|
return -1;
|
|
}
|
|
|
|
if (left >= 0 && right >= 0) {
|
|
return 1 + std::max(left, right);
|
|
}
|
|
|
|
auto t = std::abs(left) + std::abs(right);
|
|
time = std::max(time, t);
|
|
|
|
return std::min(left, right) - 1;
|
|
}
|
|
|
|
public:
|
|
int amountOfTime(TreeNode *root, int start) {
|
|
int time = 0;
|
|
dfs(root, start, time);
|
|
return time;
|
|
}
|
|
};
|