2024每日刷题(123)
Leetcode—2385. 感染二叉树需要的总时间
算法思想
参考灵神
实现代码
/**
* 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 {
public:
TreeNode* fa[100001];
int start;
TreeNode* startNode;
void dfs(TreeNode* root, TreeNode* from) {
if(root == nullptr) {
return;
}
fa[root->val] = from;
if(root->val == start) {
startNode = root;
return;
}
dfs(root->left, root);
dfs(root->right, root);
}
int maxlen(TreeNode* root, TreeNode* from) {
if(root == nullptr) {
return -1;
}
int res = -1;
if(root->left != from) {
res = max(res, maxlen(root->left, root));
}
if(root->right != from) {
res = max(res, maxlen(root->right, root));
}
if(fa[root->val] != from) {
res = max(res, maxlen(fa[root->val], root));
}
return res + 1;
}
int amountOfTime(TreeNode* root, int start) {
this->start = start;
dfs(root, nullptr);
return maxlen(startNode, startNode);
}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!