Given a binary tree, efficiently create copy of it.

Practice this problem

The idea very simple – recursively traverse the binary tree in a preorder fashion, and for each encountered node, create a new node with the same data and insert a mapping from the original tree node to the new node in a hash table. After creating the mapping, recursively process its children.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Inorder traversal of the cloned tree: 4 2 5 1 6 3 7

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