mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01: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:
parent
880aaa9179
commit
5f9d8d328b
1 changed files with 43 additions and 0 deletions
43
cpp/amount-of-time-for-binary-tree-to-be-infected.cpp
Normal file
43
cpp/amount-of-time-for-binary-tree-to-be-infected.cpp
Normal 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;
|
||||
}
|
||||
};
|
Loading…
Reference in a new issue