492. Clone Binary Tree with Random Pointer

A binary tree is given where each node contains:

  1. An integer val.
  2. 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 input

Input: 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

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a Node.
* struct Node {
* int val;
* Node *left;
* Node *right;
* Node *random;
* Node() : val(0), left(nullptr), right(nullptr), random(nullptr) {}
* Node(int x) : val(x), left(nullptr), right(nullptr), random(nullptr) {}
* Node(int x, Node *left, Node *right, Node *random) : val(x), left(left), right(right), random(random) {}
* };
*/
 
class Solution {
public:
NodeCopy* copyRandomBinaryTree(Node* root) {
// Your Code Goes Here
}
};
Test Case

Input:

Root