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; } };