/* // Definition for a Node. class Node { public: int val; vector<Node*> neighbors; Node() {} Node(int _val, vector<Node*> _neighbors) { val = _val; neighbors = _neighbors; } }; */ class Solution { public: Node* cloneGraph(Node* node) { map<int, Node*> m; return clone(node, m); } Node* clone(Node* node, map<int, Node*>& m){ if(node == NULL) return NULL; //表明这个节点已经创建了,所以没有必要重复创建,只要把已经创建的节点返回即可 if(m.find(node->val) != m.end()) return m[node->val]; //如果没有创建参数中节点,则创建,并添加到m中 Node* res = new Node(node->val); m[node->val] = res; //clone所有的邻节点,并添加到刚clone好的节点的第二个元素vector中 int len=node->neighbors.size(); for(int i=0;i<len;i++) res->neighbors.push_back(clone(node->neighbors[i], m)); return res; } };
分析:
这是别人的,我修改了一下,我可能要补一下STL了。