Approach
Breadth-first search
For Amount of Time for Binary Tree to Be Infected, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 48 lines of C++ from the credited upstream file 2385.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int amountOfTime(TreeNode* root, int start) {4 int ans = -1;5 const unordered_map<int, vector<int>> graph = getGraph(root);6 queue<int> q{{start}};7 unordered_set<int> seen{start};8 9 for (; !q.empty(); ++ans) {10 for (int sz = q.size(); sz > 0; --sz) {11 const int u = q.front();12 q.pop();13 if (!graph.contains(u))14 continue;15 for (const int v : graph.at(u)) {16 if (seen.contains(v))17 continue;18 q.push(v);19 seen.insert(v);20 }21 }22 }23 24 return ans;25 }26 27 private:28 unordered_map<int, vector<int>> getGraph(TreeNode* root) {29 unordered_map<int, vector<int>> graph;30 queue<pair<TreeNode*, int>> q{{{root, -1}}}; 31 32 while (!q.empty()) {33 const auto [node, parent] = q.front();34 q.pop();35 if (parent != -1) {36 graph[parent].push_back(node->val);37 graph[node->val].push_back(parent);38 }39 if (node->left)40 q.emplace(node->left, node->val);41 if (node->right)42 q.emplace(node->right, node->val);43 }44 45 return graph;46 }47};48