C++ recursive solution 68ms


  • 0
    B
    class Solution {
    public:
        UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) 
        {
            if(!node) return node;
            unordered_map<UndirectedGraphNode*, UndirectedGraphNode*>mp;
            return help(mp, node);
        }
        
        UndirectedGraphNode* help(unordered_map<UndirectedGraphNode*, UndirectedGraphNode*>&mp, UndirectedGraphNode *node)
        {
            if(mp.find(node)==mp.end())
            {
                UndirectedGraphNode * temp = new UndirectedGraphNode(node -> label);
                mp[node]=temp;
                for(auto e : node->neighbors)
                    temp->neighbors.push_back(help(mp,e));
            }
            return mp[node];
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.