Clone Binary Tree With Random Pointer - Problem
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
example_1.py — Basic Tree with Random Pointer
$
Input:
root = [1, null], where node 1 has random pointer to itself
›
Output:
Cloned tree with same structure and random pointer relationships
💡 Note:
Single node tree where the random pointer points to the node itself. The cloned node should also point to itself via the random pointer.
example_2.py — Tree with Cross Random Pointers
$
Input:
root = [1, 2, 3, null, null, null, null], node 2's random points to node 3
›
Output:
Cloned tree where cloned node 2's random points to cloned node 3
💡 Note:
Tree with left and right children where a leaf node's random pointer crosses to the other side of the tree. The clone must maintain this cross-reference correctly.
example_3.py — Empty Tree Edge Case
$
Input:
root = null
›
Output:
null
💡 Note:
Empty tree should return null. This tests the base case handling of the recursive solution.
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
Visualization
Tap to expand
Understanding the Visualization
1
Encounter Node
When we visit a node, check if we've already created its clone
2
Create Clone
If it's new, create the clone and immediately store the mapping
3
Handle Pointers
Recursively process left, right, and random pointers
4
Return Clone
Return the clone, which now has all connections properly established
Key Takeaway
🎯 Key Insight: Use memoization to create clones on-demand, handling forward references and cycles naturally in a single traversal
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code