Write an efficient code to clone a binary tree with each node containing an additional random pointer. The random pointer can point to any node of the binary tree or can be null.

Practice this problem

The intuitive solution to clone a binary tree with random pointers is to insert each node into a hash table. The idea is to traverse the binary tree in a preorder fashion, and for each encountered node, create a new node with the same data and create a mapping from the original node to the duplicate node in the hash table. After creating the mapping, recursively set its left and right pointers. Finally, traverse the original binary tree again and update the duplicate nodes’ random pointers using the hash table.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Preorder traversal of the original tree:
1 ——> (2, 3, 2)
2 ——> (4, 5, X)
4 ——> (X, X, 3)
5 ——> (X, X, 1)
3 ——> (6, 7, X)
6 ——> (X, X, 4)
7 ——> (X, X, X)
 
Preorder traversal of the cloned tree:
1 ——> (2, 3, 2)
2 ——> (4, 5, X)
4 ——> (X, X, 3)
5 ——> (X, X, 1)
3 ——> (6, 7, X)
6 ——> (X, X, 4)
7 ——> (X, X, X)

The time complexity of this solution is O(n), where n is the total number of nodes in the binary tree. The extra space used by the solution is O(n) for the map and call stack.