Given a Binary Tree where every node has data, a next pointer, a right pointer, and a random pointer. The random pointer points to any random node of the binary tree and can even point to NULL, the task is to clone the given binary tree.
The idea is to use hashmap to store mapping from given tree nodes to clone tree nodes in the hashtable. Then in second traversal assign each random pointer according to hash map.
Follow the steps below to solve the problem:
Traverse the original tree and create a new node for each original node, copying the data, left, and right pointers.
Use a hashmap to store the mapping between original nodes and cloned nodes.
Traverse the original tree again, using the hashmap to set the random pointers in the cloned nodes.
Return the root of the newly cloned tree.
Below is the implementation of above approach:
Output
[4 1], [2 NULL], [5 3], [1 5], [3 NULL],
Time complexity: O(n), this is because we need to traverse the entire tree in order to copy the left and right pointers, and then we need to traverse the tree again to copy the random pointers. Auxiliary Space: O(n), this is because we need to store a mapping of the original treeβs nodes to their clones.