Given a Binary Tree where every node has data, a next pointer, a right pointer, and a random pointer. The random pointer points to any random node of the binary tree and can even point to NULL, the task is to clone the given binary tree.
Example:
Approach:
The idea is to use hashmap to store mapping from given tree nodes to clone tree nodes in the hashtable. Then in second traversal assign each random pointer according to hash map.
Follow the steps below to solve the problem:
Traverse the original tree and create a new node for each original node, copying the data, left, and right pointers.
Use a hashmap to store the mapping between original nodes and cloned nodes.
Traverse the original tree again, using the hashmap to set the random pointers in the cloned nodes.
Return the root of the newly cloned tree.
Below is the implementation of above approach:
C++
// A hashmap-based C++ program to clone a binary// tree with random pointers#include<iostream>#include<unordered_map>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node*random;Node(intx){data=x;left=right=random=nullptr;}};// This function clones the tree by copying the// key (data) and left/right pointers.Node*copyLeftRightNode(Node*treeNode,unordered_map<Node*,Node*>&mp){if(treeNode==nullptr)returnnullptr;Node*cloneNode=newNode(treeNode->data);// Store the mapping between original node and cloned nodemp[treeNode]=cloneNode;// Recursively clone the left and right subtreescloneNode->left=copyLeftRightNode(treeNode->left,mp);cloneNode->right=copyLeftRightNode(treeNode->right,mp);returncloneNode;}// This function copies the random pointers using// the hashmap created in the previous step.voidcopyRandom(Node*treeNode,unordered_map<Node*,Node*>&mp){if(treeNode==nullptr)return;// Set the random pointer for the // cloned nodemp[treeNode]->random=mp[treeNode->random];// Recursively copy random pointers for left // and right subtreescopyRandom(treeNode->left,mp);copyRandom(treeNode->right,mp);}// This function creates the clone of// the given binary tree.Node*cloneTree(Node*tree){if(tree==nullptr)returnnullptr;// Create a hashmap to store the mapping// between original and cloned nodesunordered_map<Node*,Node*>mp;// Clone the tree structure // (data, left, and right pointers)Node*newTree=copyLeftRightNode(tree,mp);// Copy the random pointers using // the hashmapcopyRandom(tree,mp);returnnewTree;}// Function to print the inorder traversal of the binary tree// It also prints the random pointer of each node (or NULL if not set)voidprintInorder(Node*curr){if(curr==nullptr)return;printInorder(curr->left);cout<<"["<<curr->data<<" ";if(curr->random==nullptr)cout<<"NULL], ";elsecout<<curr->random->data<<"], ";printInorder(curr->right);}intmain(){// Constructing the binary tree with random pointers// Tree structure:// 1// / \ // 2 3// / \ // 4 5// Random pointers:// 1 -> 5, 4 -> 1, 5 -> 3Node*node=newNode(1);node->left=newNode(2);node->right=newNode(3);node->left->left=newNode(4);node->left->right=newNode(5);node->random=node->left->right;node->left->left->random=node;node->left->right->random=node->right;Node*clone=cloneTree(node);printInorder(clone);return0;}
Java
// A hashmap-based Java program to clone a binary tree with// random pointersimportjava.util.HashMap;classNode{intdata;Nodeleft,right,random;publicNode(intx){data=x;left=right=random=null;}}classGfG{// This function clones the tree by copying the// key (data) and left/right pointers.staticNodecopyLeftRightNode(NodetreeNode,HashMap<Node,Node>mp){if(treeNode==null)returnnull;NodecloneNode=newNode(treeNode.data);// Store the mapping between original node and// cloned nodemp.put(treeNode,cloneNode);// Recursively clone the left and right subtreescloneNode.left=copyLeftRightNode(treeNode.left,mp);cloneNode.right=copyLeftRightNode(treeNode.right,mp);returncloneNode;}// This function copies the random pointers using// the hashmap created in the previous step.staticvoidcopyRandom(NodetreeNode,HashMap<Node,Node>mp){if(treeNode==null)return;// Set the random pointer for the cloned nodemp.get(treeNode).random=mp.get(treeNode.random);// Recursively copy random pointers for left and// right subtreescopyRandom(treeNode.left,mp);copyRandom(treeNode.right,mp);}// Function to print the inorder traversal of the binary// tree It also prints the random pointer of each node// (or NULL if not set)staticvoidprintInorder(Nodecurr){if(curr==null)return;printInorder(curr.left);System.out.print("["+curr.data+" ");if(curr.random==null)System.out.print("NULL], ");elseSystem.out.print(curr.random.data+"], ");printInorder(curr.right);}// This function creates the clone of the given binary// tree.staticNodecloneTree(Nodetree){if(tree==null)returnnull;// Create a hashmap to store the mapping// between original and cloned nodesHashMap<Node,Node>mp=newHashMap<>();// Clone the tree structure (data, left, and right// pointers)NodenewTree=copyLeftRightNode(tree,mp);// Copy the random pointers using the hashmapcopyRandom(tree,mp);returnnewTree;}publicstaticvoidmain(String[]args){// Constructing the binary tree with random pointers// Tree structure:// 1// / \// 2 3// / \// 4 5// Random pointers:// 1 -> 5, 4 -> 1, 5 -> 3Nodenode=newNode(1);node.left=newNode(2);node.right=newNode(3);node.left.left=newNode(4);node.left.right=newNode(5);node.random=node.left.right;node.left.left.random=node;node.left.right.random=node.right;Nodeclone=cloneTree(node);printInorder(clone);}}
Python
# A hashmap-based Python program to clone a# binary tree with random pointersclassNode:def__init__(self,x):self.data=xself.left=self.right=self.random=None# Function to print the inorder traversal of the binary tree# It also prints the random pointer of each node (or NULL if not set)defprintInorder(curr):ifcurrisNone:returnprintInorder(curr.left)print(f"[{curr.data} ",end="")ifcurr.randomisNone:print("NULL], ",end="")else:print(f"{curr.random.data}], ",end="")printInorder(curr.right)# This function clones the tree by copying the# key (data) and left/right pointers.defcopyLeftRightNode(treeNode,mp):iftreeNodeisNone:returnNonecloneNode=Node(treeNode.data)# Store the mapping between original# node and cloned nodemp[treeNode]=cloneNode# Recursively clone the left and right subtreescloneNode.left=copyLeftRightNode(treeNode.left,mp)cloneNode.right=copyLeftRightNode(treeNode.right,mp)returncloneNode# This function copies the random pointers using# the hashmap created in the previous step.defcopyRandom(treeNode,mp):iftreeNodeisNone:return# Set the random pointer for# the cloned nodemp[treeNode].random=mp.get(treeNode.random)# Recursively copy random pointers for# left and right subtreescopyRandom(treeNode.left,mp)copyRandom(treeNode.right,mp)# This function creates the clone of the# given binary tree.defcloneTree(tree):iftreeisNone:returnNone# Create a hashmap to store the mapping# between original and cloned nodesmp={}# Clone the tree structure# (data, left, and right pointers)newTree=copyLeftRightNode(tree,mp)# Copy the random pointers using the hashmapcopyRandom(tree,mp)returnnewTree# Constructing the binary tree with random pointers# Tree structure:# 1# / \# 2 3# / \# 4 5# Random pointers:# 1 -> 5, 4 -> 1, 5 -> 3node=Node(1)node.left=Node(2)node.right=Node(3)node.left.left=Node(4)node.left.right=Node(5)node.random=node.left.rightnode.left.left.random=nodenode.left.right.random=node.rightclone=cloneTree(node)printInorder(clone)
C#
// A hashmap-based C# program to clone a binary tree with// random pointersusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right,random;publicNode(intx){data=x;left=right=random=null;}}classGfG{// Function to print the inorder traversal of the binary// tree It also prints the random pointer of each node// (or NULL if not set)staticvoidPrintInorder(Nodecurr){if(curr==null)return;PrintInorder(curr.left);Console.Write("["+curr.data+" ");if(curr.random==null)Console.Write("NULL], ");elseConsole.Write(curr.random.data+"], ");PrintInorder(curr.right);}// This function clones the tree by copying the// key (data) and left/right pointers.staticNodeCopyLeftRightNode(NodetreeNode,Dictionary<Node,Node>mp){if(treeNode==null)returnnull;NodecloneNode=newNode(treeNode.data);// Store the mapping between original node and// cloned nodemp[treeNode]=cloneNode;// Recursively clone the left and right subtreescloneNode.left=CopyLeftRightNode(treeNode.left,mp);cloneNode.right=CopyLeftRightNode(treeNode.right,mp);returncloneNode;}// This function copies the random pointers using// the hashmap created in the previous step.staticvoidCopyRandom(NodetreeNode,Dictionary<Node,Node>mp){if(treeNode==null)return;// Set the random pointer for the// cloned nodeif(treeNode.random!=null){mp[treeNode].random=mp[treeNode.random];}// Recursively copy random pointers for left and// right subtreesCopyRandom(treeNode.left,mp);CopyRandom(treeNode.right,mp);}// This function creates the clone of the given binary// tree.staticNodeCloneTree(Nodetree){if(tree==null)returnnull;// Create a hashmap to store the mapping// between original and cloned nodesDictionary<Node,Node>mp=newDictionary<Node,Node>();// Clone the tree structure (data, left, and right// pointers)NodenewTree=CopyLeftRightNode(tree,mp);// Copy the random pointers using the hashmapCopyRandom(tree,mp);returnnewTree;}staticvoidMain(string[]args){// Constructing the binary tree with random pointers// Tree structure:// 1// / \// 2 3// / \// 4 5// Random pointers:// 1 -> 5, 4 -> 1, 5 -> 3Nodenode=newNode(1);node.left=newNode(2);node.right=newNode(3);node.left.left=newNode(4);node.left.right=newNode(5);node.random=node.left.right;node.left.left.random=node;node.left.right.random=node.right;Nodeclone=CloneTree(node);PrintInorder(clone);}}
JavaScript
// A hashmap-based JavaScript program to clone a binary tree// with random pointersclassNode{constructor(x){this.data=x;this.left=this.right=this.random=null;}}// Function to print the inorder traversal of the binary// tree It also prints the random pointer of each node (or// NULL if not set)functionprintInorder(curr){if(curr===null)return;printInorder(curr.left);console.log(`[${curr.data} `);if(curr.random===undefined||curr.random===null)console.log("NULL], ");elseconsole.log(`${curr.random.data}], `);printInorder(curr.right);}// This function clones the tree by copying the// key (data) and left/right pointers.functioncopyLeftRightNode(treeNode,mp){if(treeNode===null)returnnull;letcloneNode=newNode(treeNode.data);// Store the mapping between original node and cloned// nodemp.set(treeNode,cloneNode);// Recursively clone the left and right subtreescloneNode.left=copyLeftRightNode(treeNode.left,mp);cloneNode.right=copyLeftRightNode(treeNode.right,mp);returncloneNode;}// This function copies the random pointers using// the hashmap created in the previous step.functioncopyRandom(treeNode,mp){if(treeNode===null)return;// Set the random pointer for the cloned nodemp.get(treeNode).random=mp.get(treeNode.random);// Recursively copy random pointers for left and right// subtreescopyRandom(treeNode.left,mp);copyRandom(treeNode.right,mp);}// This function creates the clone of the given binary tree.functioncloneTree(tree){if(tree===null)returnnull;// Create a hashmap to store the mapping// between original and cloned nodesletmp=newMap();// Clone the tree structure (data, left, and right// pointers)letnewTree=copyLeftRightNode(tree,mp);// Copy the random pointers using the hashmapcopyRandom(tree,mp);returnnewTree;}// Constructing the binary tree with random pointers// Tree structure:// 1// / \// 2 3// / \// 4 5// Random pointers:// 1 -> 5, 4 -> 1, 5 -> 3letnode=newNode(1);node.left=newNode(2);node.right=newNode(3);node.left.left=newNode(4);node.left.right=newNode(5);node.random=node.left.right;node.left.left.random=node;node.left.right.random=node.right;letclone=cloneTree(node);printInorder(clone);
Output
[4 1], [2 NULL], [5 3], [1 5], [3 NULL],
Time complexity: O(n), this is because we need to traverse the entire tree in order to copy the left and right pointers, and then we need to traverse the tree again to copy the random pointers. Auxiliary Space: O(n), this is because we need to store a mapping of the original tree’s nodes to their clones.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.