Imagine you need to create a perfect duplicate of a special binary tree where each node has an unexpected twist - besides the usual left and right child pointers, every node also has a random pointer that can point to any node in the tree (or be null).
Your mission is to create a deep copy of this tree, ensuring that:
- Every node value is copied exactly
- The structure (left/right relationships) is preserved
- All random pointers point to the correct corresponding nodes in the new tree
The challenge lies in maintaining the random pointer relationships - when you copy node A that points randomly to node B, the copied node A must point to the copied node B, not the original!
Input: Root of the original binary tree with random pointers
Output: Root of the completely independent cloned tree
Input & Output
Visualization
Time & Space Complexity
Single pass through the tree, each node visited exactly once
Hash map stores n nodes plus O(h) recursion stack space
Constraints
- The number of nodes in the tree is in the range [0, 1000]
- Each node's value is unique, and -106 โค Node.val โค 106
- The random pointer can point to any node in the tree or be null
- The tree may contain cycles through random pointers
- All Node.val are unique