2385.感染二叉树需要的总时间
思路:用树的直径思路去做,先将链表转换为邻接表的形式,然后从start开始找到最长的边即可。找法就用深度搜索dfs.
/**
* 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:
vector<int > v[100010];
void dfs(TreeNode * u){
if(u==nullptr){
return ;
}
if(u->left){
v[u->val].push_back(u->left->val);
v[u->left->val].push_back(u->val);
dfs(u->left);
}
if(u->right){
v[u->val].push_back(u->right->val);
v[u->right->val].push_back(u->val);
dfs(u->right);
}
}
int solve(int u,int fa){
int res=0;
for(int i=0;i<v[u].size();i++){
if(v[u][i]!=fa){
res=max(res,solve(v[u][i],u));
}
}
return res+1;
}
int amountOfTime(TreeNode* root, int start) {
dfs(root);//转换为邻接表的形式
int maxx=0;
for(int i=0;i<v[start].size();i++){
maxx=max(maxx,solve(v[start][i],start));//找到最长的边
}
return maxx;
}
};