492. Clone Binary Tree with Random Pointer
A binary tree is given where each node contains:
- An integer val.
- A random pointer which could point to any node in the tree or null.
You need to return a deep copy of the tree.
Input Format
The tree is represented as an array of [val, random_index] pairs:
- val: Node's integer value.
- random_index: The index of the node in the array that the random pointer points to, or null if absent.
Output Format
A deep copy of the tree in the same format.
Example 1:
Input: root = [[1,0],[0,0],[4,3],[7,0]]
Output: [[1,0],[0,0],[4,3],[7,0]]
Explanation:
The tree is:
- Node 1 has no random pointer (null).
- Node 4's random pointer points to 7 (index 3).
- Node 7's random pointer points to 1 (index 0).
Example 2:
Input: root = [[1,4],[0,0],[1,0],[0,0],[1,5],[1,5]]
Output: [[1,4],[0,0],[1,0],[0,0],[1,5],[1,5]]
Explanation:
A valid tree where nodes can have their random pointer pointing to themselves.
Now Your Turn!
Pick the correct output for the given inputInput: root = [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- The number of nodes in the tree is in the range [0, 1000].
- 1 <= Node.val <= 106