LeetCode:1484. 克隆含随机指针的二叉树(方法1:hash_map+DFS 方法2:两次DFS, C++带详细注释)
/**
* Definition for a binary tree 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 {//官方dfs+hash_map
// public:
// unordered_map<Node*, NodeCopy*>map;//建立一个hash_map
// NodeCopy* copyRandomBinaryTree(Node* root) {
// if(root==nullptr) return nullptr;
// if(map.count(root)) return map[root];//哈希图中有对应的直接返回
// NodeCopy*TR=new NodeCopy(root->val);//建立一个节点
// map[root]=TR;//建立映射关系
// TR->left=copyRandomBinaryTree(root->left);//递归建立以下三指针
// TR->right=copyRandomBinaryTree(root->right);
// TR->random=copyRandomBinaryTree(root->random);
// return TR;
// }
// };
class Solution {//官方:两次dfs,一次建立树,一次建立random节点
public:
unordered_map<Node*, NodeCopy*> orig_dupli_map;//建立hashmap
void copy_tree(Node* root, NodeCopy* &target)//递归复制树
{
if(root == NULL)return;
target = new NodeCopy(root->val);//要建立新节点
orig_dupli_map[root] = target;//并且建立对应节点映射关系
copy_tree(root->left, target->left);//递归复制左右子树
copy_tree(root->right, target->right);
}
void fill_random(Node* root, NodeCopy* target)//递归复制random节点
{
if(root == NULL)return;
target->random = orig_dupli_map[root->random];//从映射关系中取出
fill_random(root->left, target->left);//递归复制左右子树的random节点
fill_random(root->right, target->right);
}
NodeCopy* copyRandomBinaryTree(Node* root) {
NodeCopy *target = NULL;
copy_tree(root, target);//建立树
fill_random(root, target);//建立random节点
return target;//返回
}
};