Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.6 kB
3
Indexable
Never
class Solution{

    public:
    int ladoos(Node* root, int home, int k)
    {
        // map to store node -> parent
        unordered_map<Node*,Node*>m;
        queue<Node*>q;
        q.push(root);
        Node* need;
        while(!q.empty())
        {
            int size=q.size();
            for(int i=0;i<size;i++)
            {
               Node* node = q.front();
               q.pop();
               if(home==node->data)need=node;
               if(node->left)
               {q.push(node->left);
                m[node->left]=node;
               }
               if(node->right)
               {
                   q.push(node->right);
                   m[node->right]=node;
               }
               
            }
            
        }
        
        unordered_map<Node*,bool>mp;
        q.push(need);
        int sum=0;
        while(!q.empty() && k+1)
        {
           int s=q.size();
           for(int i=0;i<s;i++)
           {
                Node* temp=q.front();
                q.pop();
                mp[temp]=true;
                sum+=temp->data;
                if(temp->left && mp[temp->left]==false)
                {
                   q.push(temp->left);
                }
                if(temp->right && mp[temp->right]==false)
                {
                    q.push(temp->right);
                }
                if(m[temp] && mp[m[temp]]==false)
                {
                    q.push(m[temp]);
                }
                
           }
           
           k--;
            
        }
        return sum;
        // Your code goes here
    }


};