1. Full Tree to Graph Conversion + BFS
Intuition
Convert tree into an undirected graph representation with adjacency lists. Then run standard BFS from target vertex until all reachable vertices are visited.
When to apply: Basic baseline check.
Algorithm
- Step 1: Traverse tree to create bidirectional adjacency list adj[u].push(v) and adj[v].push(u).
- Step 2: Initialize queue with target, visited set with target.
- Step 3: Track levels. For each level, pop all current nodes and enqueue unvisited neighbors.
- Step 4: Return total level count - 1.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: void buildGraph(TreeNode* node, TreeNode* parent, unordered_map<int, vector<int>>& adj) { if (!node) return; if (parent) { adj[node->val].push_back(parent->val); adj[parent->val].push_back(node->val); } buildGraph(node->left, node, adj); buildGraph(node->right, node, adj); } int minTime(TreeNode* root, int target) { unordered_map<int, vector<int>> adj; buildGraph(root, nullptr, adj); queue<int> q; unordered_set<int> visited; q.push(target); visited.insert(target); int time = 0; while (!q.empty()) { int sz = q.size(); bool burned = false; for (int i = 0; i < sz; ++i) { int curr = q.front(); q.pop(); for (int nxt : adj[curr]) { if (!visited.count(nxt)) { visited.insert(nxt); q.push(nxt); burned = true; } } } if (burned) time++; } return time; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Graph creation takes O(n); BFS visits all n nodes. - Space complexity:
O(n)— Graph adjacency list stores 2*(n-1) edges.