图节点的深拷贝

问题描述 投票:0回答:0

我正在解决 LeetCode 问题 #133 给定一个连通无向图的节点指针。 节点结构包含节点的值和相邻节点的向量。我们必须归还它的深层副本。

这是我的代码:

class Solution {
public:

    void clone (
        const Node *NODE,
        Node *node,
        vector<Node *>& nodes,
        vector<bool>& visited
    ) {
        if ( visited[node->val] ) return;
        else visited[node->val] = true;

        cout << "On node : " << node->val << endl;

        Node *temp;

        for ( Node* next : NODE->neighbors ) {
            if ( !nodes[next->val] ) {
                temp = new Node(next->val);
                nodes[next->val] = temp;
            }
            temp = nodes[next->val];
            cout << next->val << " now neighbour of " << node->val << endl;
            (node->neighbors).push_back(temp);

            clone(next, temp, nodes, visited);
        }
    }

    Node* cloneGraph(Node* node) {

        if ( !node ) return NULL;

        vector<Node *> nodes(101, NULL);
        vector<bool> visited(101, false);

        Node *root = new Node(node->val);

        clone(  node, root, nodes, visited );

        return root;
    }
};

我不知道这里出了什么问题。它似乎可以很好地创建节点和设置邻居,但我收到此错误:

You must return a copy of all the nodes in the original graph

这是测试用例:

[[2,4],[1,3],[2,4],[1,3]]

标准输出:

On node : 1
2 now neighbour of 1
On node : 2
1 now neighbour of 2
3 now neighbour of 2
On node : 3
2 now neighbour of 3
4 now neighbour of 3
On node : 4
1 now neighbour of 4
3 now neighbour of 4
4 now neighbour of 1
c++ pointers data-structures graph
© www.soinside.com 2019 - 2024. All rights reserved.