You are given a binary tree where each node has a left child, a right child, and a random pointer that points to any node in the tree or null. You need to create a "deep copy" of this tree. A deep copy means all nodes in the new tree must be new instances, and all pointers (including the random ones) must point to the corresponding nodes in the new tree.
Meta and Amazon use this "Medium" problem to test your ability to handle complex object references and graph traversal. It’s a variation of the "Clone Graph" problem. The main challenge is that when you are cloning a node, its random pointer might point to a node you haven't created yet. It evaluations your skill in using a Hash Table to map original nodes to their copies.
The pattern is Graph Traversal (DFS or BFS) with a Hash Table.
map[old_node] = new_node.left, right, and random pointers of the new nodes using the map: new_node.random = map[old_node.random].map[A] = A'.map[B] = B'.map[C] = C'.A'.left = map[B] = B'.A'.random = map[C] = C'.
This ensures the copy structure exactly mirrors the original.The most common mistake is a "shallow copy," where the new tree still points to nodes in the original tree. Another is not handling null pointers correctly. Some might also try to solve it without a map, which is much more difficult and usually requires multiple passes or structural modifications to the original tree.
Any "cloning" problem involving random or arbitrary pointers requires a way to "remember" which copy corresponds to which original. A Hash Table (Map) is the most straightforward and efficient way to achieve this.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Lowest Common Ancestor of Deepest Leaves | Medium | Solve | |
| Find Distance in a Binary Tree | Medium | Solve | |
| Smallest Subtree with all the Deepest Nodes | Medium | Solve | |
| Cousins in Binary Tree II | Medium | Solve | |
| All Nodes Distance K in Binary Tree | Medium | Solve |