Problem Description
Given a binary tree where every node has an additional pointer called "random" that can point to any node in the tree (or null), create a deep copy of the tree. Each node in the input tree is represented as a pair [val, random_index] (along with standard left/right pointer structure), and the output should mirror the same structure. The challenge lies in copying both the tree connections (left/right) and the arbitrary random pointer links correctly.
Key Insights
- Use a hash table (or dictionary) to map each original node to its corresponding cloned node.
- Traverse the tree (using DFS or BFS) to clone the nodes without worrying initially about their random pointers.
- In a second traversal, update the left, right, and random pointers in the cloned nodes by referring to the mapping.
- Handle null cases carefully to avoid dereferencing null pointers.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes, as we traverse all nodes. Space Complexity: O(n), needed to store the mapping/dictionary and the cloned nodes.
Solution
The approach used is a two-pass traversal:
- First, perform a traversal (DFS or BFS) to create a copy of every node. During this phase, use a hash table to map each original node to its new copy. This helps in later connecting the pointers correctly.
- Second, traverse the tree again and set the left, right, and random pointers for each cloned node. For each pointer, refer to the hash table to find the corresponding cloned node. Key data structures:
- A dictionary (or hash map) to store the mapping between original nodes and their clones.
- Recursive or iterative traversal (DFS/BFS) to process each node.
The trick is to ensure that whenever you are about to set a pointer (left, right, or random), you have already created the corresponding copy or can create it on the fly using the mapping.