1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00

cpp: add “2385. Amount of Time for Binary Tree to Be Infected”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-01-10 22:28:23 +01:00
parent 880aaa9179
commit 5f9d8d328b
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,43 @@
/**
* 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;
}
};