[LeetCode] Clone Binary Tree With Random Pointer

1485. Clone Binary Tree With Random Pointer

A binary tree is given such that each node contains an additional random pointer which could point to any node in the tree or null.

Return a deep copy of the tree.

The tree is represented in the same input/output way as normal binary trees where each node is represented as a pair of [val, random_index] where:

  • val: an integer representing Node.val
  • random_index: the index of the node (in the input) where the random pointer points to, or null if it does not point to any node.

You will be given the tree in class Node and you should return the cloned tree in class NodeCopy. NodeCopy class is just a clone of Node class with the same attributes and constructors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* 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 {
unordered_map<Node*, NodeCopy*> mp;
void dfs(Node* node) {
if(!node) return;
mp[node] = new NodeCopy(node->val);
dfs(node->left);
dfs(node->right);
}
NodeCopy* dfs2(Node* node) {
if(!node) return nullptr;
auto res = mp[node];
res->left = dfs2(node->left);
res->right = dfs2(node->right);
if(node->random)
res->random = mp[node->random];
return res;
}
public:
NodeCopy* copyRandomBinaryTree(Node* root) {
dfs(root);
return dfs2(root);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/29/PS/LeetCode/clone-binary-tree-with-random-pointer/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.