Advertisement
imashutosh51

Burning Tree

Jul 31st, 2022
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. /*
  2. Logic:We can do this while BFS traversal,so we can go down but we can't go up in tree so
  3. we created a map in which we will store parent address and do bfs
  4. similary created a visited map,which will take care of viisted nodes.
  5.  
  6. Method 2:we can do this in single travesal by levelordertraversal storing parents in map
  7. and when we acheived target we will start bfs algorithm from there.because we won't need
  8. the parent of lower level nodes than the target level node.
  9. */
  10.  
  11. void dfs(Node *root,unordered_map<Node*,Node*> &mp){
  12.     if(!root) return;
  13.     if(root->left){ mp[root->left]=root;dfs(root->left,mp);}
  14.     if(root->right){ mp[root->right]=root;dfs(root->right,mp);}
  15. }
  16. Node* find_node(Node *root,int target){
  17.     if(!root) return NULL;
  18.     if(root->data==target) return root;
  19.     Node *t1=find_node(root->left,target);
  20.     Node *t2=find_node(root->right,target);
  21.     if(t1) return t1;
  22.     else return t2;
  23. }
  24. class Solution {
  25.   public:
  26.     int minTime(Node* root, int target) {
  27.        unordered_map<Node*,Node*> mp;
  28.        unordered_map<Node*,bool> visited;
  29.       dfs(root,mp);
  30.       Node* target_node=find_node(root,target);
  31.       deque<Node*> q;
  32.       q.push_back(target_node);
  33.       int time=0;
  34.       visited[target_node]=true;
  35.       while(q.size()){
  36.           int k=q.size();
  37.           for(int i=0;i<k;i++){
  38.               Node *temp=q.front();
  39.               q.pop_front();
  40.               if(temp->left && !visited[temp->left]){ q.push_back(temp->left);visited[temp->left]=true;}
  41.               if(temp->right && !visited[temp->right]){q.push_back(temp->right);visited[temp->right]=true;}
  42.               if(temp!=root && !visited[mp[temp]]){ q.push_back(mp[temp]);  visited[mp[temp]]=true;}
  43.           }
  44.           time++;
  45.       }
  46.       return time-1;
  47.     }
  48. };
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement