Clone a Binary Tree | Practice | GeeksforGeeks

Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.

Example 1:
Input:

Output: 1
Explanation: The tree was cloned successfully.


Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree. 
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).

Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000
+1
wolfofsv4 days ago
Single traversal
create and store root (if not created before)
create and store the random node (if not created before)
clone left subtree
clone right subtree
Node* Inorder(Node* root, unordered_map<Node*, Node*>& origToDup){
        if(root){
            if(origToDup.find(root) == origToDup.end()){
                Node* newNode = new Node(root -> data);
                origToDup[root] = newNode;
            }
            
            if(root -> random && origToDup.find(root -> random) == origToDup.end()){
                Node* newNode = new Node(root -> random -> data);
                origToDup[root -> random] = newNode;
            }
            
            origToDup[root] -> random = origToDup[root -> random];
            origToDup[root] -> left = Inorder(root -> left, origToDup);
            origToDup[root] -> right = Inorder(root -> right, origToDup);
            
            return origToDup[root];
        }
        return NULL;
    }
       
    Node* cloneTree(Node* tree)
    {
       //Your code here
       unordered_map<Node*, Node*>origToDup;
       return Inorder(tree, origToDup);
    }
+1
aryangarg1999
This comment was deleted.
0
amit092 weeks ago
class Solution{
   std::map<Node*, Node*> cloneMap;
 public:
   /* The function should clone the passed tree and return 
      root of the cloned tree */
   void mapRandomNode(Node * tree){
       if(!tree) return;
       
       cloneMap[tree]->random = cloneMap[tree->random];
       mapRandomNode(tree->left);
       mapRandomNode(tree->right);
   }
   Node * cloneTreeHelper(Node * tree)
   {
       if(tree == NULL) return tree;
      
       Node * cloneNode = new Node(tree->data);
       cloneMap[tree] = cloneNode;
       cloneNode->left = cloneTreeHelper(tree->left);
       cloneNode->right = cloneTreeHelper(tree->right);
   }
   Node* cloneTree(Node* tree)
   {
      //Your code here
      if(!tree) return nullptr;
      Node * retTree = cloneTreeHelper(tree);
      mapRandomNode(tree);
      
      return retTree;
   }
};
+1
prasannathapa3 weeks ago
Node* cloneTree(Node* tree)
   {
      if(!tree) return NULL;
      Node* newNode = new Node(tree->data);
      newNode->left = cloneTree(tree->left);
      newNode->right = cloneTree(tree->right);
      newNode->random = tree->random;
      return newNode;
   }
0
roopsaisurampudi1 month ago
Java Solution using HashMap
 public void solve(Tree root, HashMap<Tree, Tree> hm) {
        if (root == null) return;
        hm.put(root, new Tree(root.data));
        solve(root.left, hm);
        solve(root.right, hm);
    }
    
    public void solveTree(Tree root, HashMap<Tree, Tree> hm) {
        if (root == null) return;
        Tree node = hm.get(root);
        node.left = hm.get(root.left);
        node.right = hm.get(root.right);
        node.random = hm.get(root.random);
        solveTree(root.left, hm);
        solveTree(root.right, hm);
    }
    public Tree cloneTree(Tree tree){
       // add code here.
       HashMap<Tree, Tree> hm = new HashMap<>();
       solve(tree, hm);
       solveTree(tree, hm);
       return hm.get(tree);
     }
0
shulabhgill2 months ago
 Node* create_copy(Node* root,unordered_map<Node *, Node *> &mp){         if(!root)         return NULL;                  mp[root]=new Node(root->data);         mp[root]->left=create_copy(root->left,mp);          mp[root]->right=create_copy(root->right,mp);          return mp[root];              }     void create_random(Node* tree,unordered_map<Node *, Node *> &mp){                  if(!tree)         return NULL;                  mp[tree]->random=mp[tree->random];         create_random(tree->left,mp);         create_random(tree->right,mp);                                }   Node* cloneTree(Node* tree)   {      if(!tree)      return NULL;            unordered_map<Node *, Node *>mp;            Node * root=create_copy(tree,mp);       create_random(tree,mp);            return root;         }};
0
madhukartemba2 months ago
EASY JAVA SOLUTION USING HASHMAP:
class Solution
{
    private Tree rec(Tree node, HashMap<Integer, Tree> map)
    {
        if(node==null) return null;
        
        Tree root;
        
        if(map.containsKey(node.data))
        {
            //The node already exists so we don't create a new node.
            root = map.get(node.data);
        }
        else
        {
            //The node does not exist so we create a new node and add it to the HashMap.
            root = new Tree(node.data);
            map.put(root.data, root);
        }
        
        
        if(node.random!=null)
        {
            //If the node's random pointer is not null
            if(map.containsKey(node.random.data))
            {
                //If the map contains node.random
                root.random = map.get(node.random.data);
            }
            else
            {
                //Else create a new node and add it to the map.
                root.random = new Tree(node.random.data);
                map.put(root.random.data, root.random);
            }
        }
        
        //Recursively travel left and right;
        root.left = rec(node.left, map);
        root.right = rec(node.right, map);
        
        //Return the root;
        return root;
    }
    
    public Tree cloneTree(Tree tree)
    {
        Tree root = rec(tree, new HashMap<>());
        return root;
    }
}
+4
harshit68rocking2 months ago
    Node* cloneTree(Node* tree)
    {
        
       //Your code here
       if(tree== NULL) return NULL;
       
        Node *root = new Node(tree->data);
        root->data = tree->data;
        root->random = tree->random;
        root->left =  cloneTree(tree->left);
        root->right =  cloneTree(tree->right);
       return root;
    }
+1
greatwhite2 months ago
C++ solution
class Solution{
  public:
    unordered_map<Node*, Node*> dp;
       
    Node* copyTree(Node* root) {
        if(!root) return NULL;
        Node* newRoot = new Node(root->data);
        dp[root] = newRoot;
        newRoot->left = copyTree(root->left);
        newRoot->right = copyTree(root->right);
        return newRoot;
    }
    
    void copyRandom(Node* root, Node* newRoot) {
        if(!root) return;
        newRoot->random = dp[root->random];
        copyRandom(root->left, newRoot->left);
        copyRandom(root->right, newRoot->right);
    }
    
    Node* cloneTree(Node* tree) {
       Node* newRoot = copyTree(tree);
       copyRandom(tree, newRoot);
       return newRoot;
    }
};
0
hamidnourashraf2 months ago
    def simple_clone(self, root):
        if root is None:
            return None
        else:
            new_root = Node(root.data)
            if root.random:
                new_root.random = Node(root.random.data)
            new_root.left = self.simple_clone(root.left)
            new_root.right = self.simple_clone(root.right)
            
        return new_root
        
    def cloneTree(self, root):
        new_root = self.simple_clone(root)
        
        return new_root
 
There is a problem in the way the original tree is created. The parent node in random field is not exactly the object of parent. So the random field is not referring to parent node object but a new object has been created with the same data as data in parent. 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.