[CareerCup] 13.7 Node Pointer 节点指针

 

13.7 Write a method that takes a pointer to a Node structure as a parameter and returns a complete copy of the passed in data structure. The Node data structure contains two pointers to other Nodes.

 

在这道题让我们通过一个节点指针来复制整个数据结构,节点类Node中包含两个节点指针,我们需要用哈希表来建立原数据结构中每一个节点的地址到相对应的新结构中的地址,这样我们就可以在用DFS的时候知道哪些节点我们已经拷贝过了,就可以直接跳过。通过这种方式来标记访问过的节点可以不用在节点内部存储。拷贝过程如下所示:

 

class Node {
public:
    Node *ptr1;
    Node *ptr2;
};

typedef unordered_map<Node*, Node*> NodeMap;

class Solution {
public:
    Node* copy_structure(Node *root) {
        NodeMap m;
        return copy_recursive(root, m);
    }
    Node* copy_recursive(Node *cur, NodeMap &m) {
        if (cur == nullptr) return nullptr;
        auto it = m.find(cur);
        if (it != m.end()) return it->second;
        Node *node = new Node;
        m[cur] = node;
        node->ptr1 = copy_recursive(cur->ptr1, m);
        node->ptr2 = copy_recursive(cur->ptr2, m);
        return node;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值