个人练习-Leetcode-2385. Amount of Time for Binary Tree to Be Infected

该问题涉及计算从指定节点开始,二叉树完全被感染所需的时间。使用深度优先搜索(DFS)来构建节点的邻居关系,然后用广度优先搜索(BFS)模拟感染过程,直到所有节点都被感染。关键在于DFS构建邻接表和BFS遍历并更新感染状态。
摘要由CSDN通过智能技术生成

题目链接:https://leetcode.cn/problems/amount-of-time-for-binary-tree-to-be-infected/

题目大意:给一棵二叉树,其中元素各异。给一个节点的元素start,第0分钟时它是感染源。然后之后的每一分钟,被感染的节点都会传染其儿子节点和父亲节点。求整棵树被感染的时间。

思路:DFS+BFS。DFS记录邻居节点(父亲节点和儿子节点),BFS模拟感染过程。

完整代码

/**
 * 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> neb[100001];
    vector<bool> infected;
    set<int> uninf;


    void dfs(TreeNode* node, int parent) {
        if (node == nullptr)
            return;
        uninf.insert(node->val);
        if (parent != 0)
            neb[node->val].push_back(parent);
        if (node->left) {
            neb[node->val].push_back(node->left->val);
            dfs(node->left, node->val);
        }
        if (node->right) {
            neb[node->val].push_back(node->right->val);
            dfs(node->right, node->val);
        }
    }

    void infect(int infected, int mnt) {


    }

    int amountOfTime(TreeNode* root, int start) {
        dfs(root, 0);

        infected.resize(100001, false);
        int mnt = -1;
        vector<int> nxt;
        vector<int> now_inf;
        nxt.push_back(start);
        while(!uninf.empty()) {
            mnt++;
            now_inf = nxt;
            nxt.clear();
            for (int i = 0; i < now_inf.size(); i++) {
                infected[now_inf[i]] = true;
                uninf.erase(now_inf[i]);
                if (uninf.empty())
                    break;
                for (int j = 0; j < neb[now_inf[i]].size(); j++) {
                    if (!infected[neb[now_inf[i]][j]]) {
                        nxt.push_back(neb[now_inf[i]][j]);
                    }
                }
            }  
        }

        return mnt;




    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值