package com.flang.clone;

import java.util.HashMap;
import java.util.Map;

public class CloneBinaryTreeWithRandomPointer {

    Map<TreeNode, TreeNode> map=new HashMap<>();
    
    public TreeNode cloneTree(TreeNode root) {
        return deepCopy(root);
    }

    private TreeNode deepCopy(TreeNode root) {
        if (root == null) return null;
        if (map.get(root) != null) {
            return map.get(root);
        }
        TreeNode copy = new TreeNode(root.data);
        map.put(root, copy);
        copy.left = deepCopy(root.left);
        copy.right = deepCopy(root.right);
        copy.random = deepCopy(root.random);
        return copy;
    }
}

@@ -170,13 +170,9 @@
 ();%0A
-    
 %0A
+
     
@@ -338,16 +338,87 @@
 n null;%0A
+        // if the node is already being copied, return the copied node%0A
         
@@ -568,16 +568,41 @@
  copy);%0A
+        // dfs left node%0A
         
@@ -630,24 +630,50 @@
 root.left);%0A
+        // dfs right node%0A
         copy
@@ -699,24 +699,24 @@
 oot.right);%0A
-
         copy
@@ -748,16 +748,44 @@
 andom);%0A
+        // return copy node%0A
         

Update CloneBinaryTreeWithRandomPointer.java