Clone Binary Tree With Random Pointer

medium tree dfs bfs hash map

Problem

Given a binary tree where each node also has a random pointer, return a deep copy preserving left, right, and random links.

Inputtree [1,null,4,7,3,null,null,#] with random links
Outputdeep clone with identical structure
Use a NodeOriginal → NodeCloned hash map.

def copy_random_binary_tree(root):
    if not root: return None
    seen = {}
    def clone(n):
        if not n: return None
        if n in seen: return seen[n]
        nc = Node(n.val); seen[n] = nc
        nc.left = clone(n.left); nc.right = clone(n.right); nc.random = clone(n.random)
        return nc
    return clone(root)
function copyRandomBinaryTree(root) {
  const seen = new Map();
  function clone(n) {
    if (!n) return null;
    if (seen.has(n)) return seen.get(n);
    const nc = { val: n.val, left: null, right: null, random: null };
    seen.set(n, nc);
    nc.left = clone(n.left); nc.right = clone(n.right); nc.random = clone(n.random);
    return nc;
  }
  return clone(root);
}
class Solution {
    Map seen = new HashMap<>();
    public NodeCopy copyRandomBinaryTree(Node root) {
        if (root == null) return null;
        if (seen.containsKey(root)) return seen.get(root);
        NodeCopy n = new NodeCopy(root.val);
        seen.put(root, n);
        n.left = copyRandomBinaryTree(root.left);
        n.right = copyRandomBinaryTree(root.right);
        n.random = copyRandomBinaryTree(root.random);
        return n;
    }
}
class Solution {
    unordered_map seen;
public:
    NodeCopy* copyRandomBinaryTree(Node* root) {
        if (!root) return nullptr;
        if (seen.count(root)) return seen[root];
        NodeCopy* n = new NodeCopy(root->val);
        seen[root] = n;
        n->left = copyRandomBinaryTree(root->left);
        n->right = copyRandomBinaryTree(root->right);
        n->random = copyRandomBinaryTree(root->random);
        return n;
    }
};
Time: O(n) Space: O(n)