Clone Binary Tree With Random Pointer
给一个二叉树, 里面有random pointer, 求deep copy这个二叉树.
/**
* Definition for a Node.
* struct Node {
* int val;
* Node *left;
* Node *right;
* Node *random;
* Node() : val(0), left(nullptr), right(nullptr), random(nullptr) {}
* Node(int x) : val(x), left(nullptr), right(nullptr), random(nullptr) {}
* Node(int x, Node *left, Node *right, Node *random) : val(x), left(left), right(right), random(random) {}
* };
*/
class Solution {
public:
NodeCopy* copyRandomBinaryTree(Node* root) {
unordered_map<Node*, NodeCopy*> map;
return copy(root, map);
}
NodeCopy* copy(Node* root, unordered_map<Node*, NodeCopy*>& map) {
if(root == nullptr)
return nullptr;
if(map.find(root) != map.end())
return map[root];
NodeCopy* nodecopy = new NodeCopy(root->val);
map[root] = nodecopy;
nodecopy->left = copy(root->left, map);
nodecopy->right = copy(root->right, map);
nodecopy->random = copy(root->random, map);
return nodecopy;
}
};