Clone a Binary Tree with Random Pointers
Last Updated :
23 Jul, 2025
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>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node *random;
Node(int x) {
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)
return nullptr;
Node *cloneNode = new Node(treeNode->data);
// Store the mapping between original node and cloned node
mp[treeNode] = cloneNode;
// Recursively clone the left and right subtrees
cloneNode->left = copyLeftRightNode(treeNode->left, mp);
cloneNode->right = copyLeftRightNode(treeNode->right, mp);
return cloneNode;
}
// This function copies the random pointers using
// the hashmap created in the previous step.
void copyRandom(Node *treeNode,
unordered_map<Node *, Node *> &mp) {
if (treeNode == nullptr)
return;
// Set the random pointer for the
// cloned node
mp[treeNode]->random = mp[treeNode->random];
// Recursively copy random pointers for left
// and right subtrees
copyRandom(treeNode->left, mp);
copyRandom(treeNode->right, mp);
}
// This function creates the clone of
// the given binary tree.
Node *cloneTree(Node *tree) {
if (tree == nullptr)
return nullptr;
// Create a hashmap to store the mapping
// between original and cloned nodes
unordered_map<Node *, Node *> mp;
// Clone the tree structure
// (data, left, and right pointers)
Node *newTree = copyLeftRightNode(tree, mp);
// Copy the random pointers using
// the hashmap
copyRandom(tree, mp);
return newTree;
}
// Function to print the inorder traversal of the binary tree
// It also prints the random pointer of each node (or NULL if not set)
void printInorder(Node *curr) {
if (curr == nullptr)
return;
printInorder(curr->left);
cout << "[" << curr->data << " ";
if (curr->random == nullptr)
cout << "NULL], ";
else
cout << curr->random->data << "], ";
printInorder(curr->right);
}
int main() {
// Constructing the binary tree with random pointers
// Tree structure:
// 1
// / \
// 2 3
// / \
// 4 5
// Random pointers:
// 1 -> 5, 4 -> 1, 5 -> 3
Node *node = new Node(1);
node->left = new Node(2);
node->right = new Node(3);
node->left->left = new Node(4);
node->left->right = new Node(5);
node->random = node->left->right;
node->left->left->random = node;
node->left->right->random = node->right;
Node *clone = cloneTree(node);
printInorder(clone);
return 0;
}
Java
// A hashmap-based Java program to clone a binary tree with
// random pointers
import java.util.HashMap;
class Node {
int data;
Node left, right, random;
public Node(int x) {
data = x;
left = right = random = null;
}
}
class GfG {
// This function clones the tree by copying the
// key (data) and left/right pointers.
static Node copyLeftRightNode(Node treeNode,
HashMap<Node, Node> mp) {
if (treeNode == null)
return null;
Node cloneNode = new Node(treeNode.data);
// Store the mapping between original node and
// cloned node
mp.put(treeNode, cloneNode);
// Recursively clone the left and right subtrees
cloneNode.left
= copyLeftRightNode(treeNode.left, mp);
cloneNode.right
= copyLeftRightNode(treeNode.right, mp);
return cloneNode;
}
// This function copies the random pointers using
// the hashmap created in the previous step.
static void copyRandom(Node treeNode,
HashMap<Node, Node> mp) {
if (treeNode == null)
return;
// Set the random pointer for the cloned node
mp.get(treeNode).random
= mp.get(treeNode.random);
// Recursively copy random pointers for left and
// right subtrees
copyRandom(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)
static void printInorder(Node curr) {
if (curr == null)
return;
printInorder(curr.left);
System.out.print("[" + curr.data + " ");
if (curr.random == null)
System.out.print("NULL], ");
else
System.out.print(curr.random.data + "], ");
printInorder(curr.right);
}
// This function creates the clone of the given binary
// tree.
static Node cloneTree(Node tree) {
if (tree == null)
return null;
// Create a hashmap to store the mapping
// between original and cloned nodes
HashMap<Node, Node> mp = new HashMap<>();
// Clone the tree structure (data, left, and right
// pointers)
Node newTree = copyLeftRightNode(tree, mp);
// Copy the random pointers using the hashmap
copyRandom(tree, mp);
return newTree;
}
public static void main(String[] args) {
// Constructing the binary tree with random pointers
// Tree structure:
// 1
// / \
// 2 3
// / \
// 4 5
// Random pointers:
// 1 -> 5, 4 -> 1, 5 -> 3
Node node = new Node(1);
node.left = new Node(2);
node.right = new Node(3);
node.left.left = new Node(4);
node.left.right = new Node(5);
node.random = node.left.right;
node.left.left.random = node;
node.left.right.random = node.right;
Node clone = cloneTree(node);
printInorder(clone);
}
}
Python
# A hashmap-based Python program to clone a
# binary tree with random pointers
class Node:
def __init__(self, x):
self.data = x
self.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)
def printInorder(curr):
if curr is None:
return
printInorder(curr.left)
print(f"[{curr.data} ", end="")
if curr.random is None:
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.
def copyLeftRightNode(treeNode, mp):
if treeNode is None:
return None
cloneNode = Node(treeNode.data)
# Store the mapping between original
# node and cloned node
mp[treeNode] = cloneNode
# Recursively clone the left and right subtrees
cloneNode.left = copyLeftRightNode(treeNode.left, mp)
cloneNode.right = copyLeftRightNode(treeNode.right, mp)
return cloneNode
# This function copies the random pointers using
# the hashmap created in the previous step.
def copyRandom(treeNode, mp):
if treeNode is None:
return
# Set the random pointer for
# the cloned node
mp[treeNode].random = mp.get(treeNode.random)
# Recursively copy random pointers for
# left and right subtrees
copyRandom(treeNode.left, mp)
copyRandom(treeNode.right, mp)
# This function creates the clone of the
# given binary tree.
def cloneTree(tree):
if tree is None:
return None
# Create a hashmap to store the mapping
# between original and cloned nodes
mp = {}
# Clone the tree structure
# (data, left, and right pointers)
newTree = copyLeftRightNode(tree, mp)
# Copy the random pointers using the hashmap
copyRandom(tree, mp)
return newTree
# Constructing the binary tree with random pointers
# Tree structure:
# 1
# / \
# 2 3
# / \
# 4 5
# Random pointers:
# 1 -> 5, 4 -> 1, 5 -> 3
node = Node(1)
node.left = Node(2)
node.right = Node(3)
node.left.left = Node(4)
node.left.right = Node(5)
node.random = node.left.right
node.left.left.random = node
node.left.right.random = node.right
clone = cloneTree(node)
printInorder(clone)
C#
// A hashmap-based C# program to clone a binary tree with
// random pointers
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right, random;
public Node(int x) {
data = x;
left = right = random = null;
}
}
class GfG {
// Function to print the inorder traversal of the binary
// tree It also prints the random pointer of each node
// (or NULL if not set)
static void PrintInorder(Node curr) {
if (curr == null)
return;
PrintInorder(curr.left);
Console.Write("[" + curr.data + " ");
if (curr.random == null)
Console.Write("NULL], ");
else
Console.Write(curr.random.data + "], ");
PrintInorder(curr.right);
}
// This function clones the tree by copying the
// key (data) and left/right pointers.
static Node
CopyLeftRightNode(Node treeNode,
Dictionary<Node, Node> mp) {
if (treeNode == null)
return null;
Node cloneNode = new Node(treeNode.data);
// Store the mapping between original node and
// cloned node
mp[treeNode] = cloneNode;
// Recursively clone the left and right subtrees
cloneNode.left
= CopyLeftRightNode(treeNode.left, mp);
cloneNode.right
= CopyLeftRightNode(treeNode.right, mp);
return cloneNode;
}
// This function copies the random pointers using
// the hashmap created in the previous step.
static void
CopyRandom(Node treeNode, Dictionary<Node, Node> mp) {
if (treeNode == null)
return;
// Set the random pointer for the
// cloned node
if (treeNode.random != null) {
mp[treeNode].random = mp[treeNode.random];
}
// Recursively copy random pointers for left and
// right subtrees
CopyRandom(treeNode.left, mp);
CopyRandom(treeNode.right, mp);
}
// This function creates the clone of the given binary
// tree.
static Node CloneTree(Node tree) {
if (tree == null)
return null;
// Create a hashmap to store the mapping
// between original and cloned nodes
Dictionary<Node, Node> mp
= new Dictionary<Node, Node>();
// Clone the tree structure (data, left, and right
// pointers)
Node newTree = CopyLeftRightNode(tree, mp);
// Copy the random pointers using the hashmap
CopyRandom(tree, mp);
return newTree;
}
static void Main(string[] args) {
// Constructing the binary tree with random pointers
// Tree structure:
// 1
// / \
// 2 3
// / \
// 4 5
// Random pointers:
// 1 -> 5, 4 -> 1, 5 -> 3
Node node = new Node(1);
node.left = new Node(2);
node.right = new Node(3);
node.left.left = new Node(4);
node.left.right = new Node(5);
node.random = node.left.right;
node.left.left.random = node;
node.left.right.random = node.right;
Node clone = CloneTree(node);
PrintInorder(clone);
}
}
JavaScript
// A hashmap-based JavaScript program to clone a binary tree
// with random pointers
class Node {
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)
function printInorder(curr) {
if (curr === null)
return;
printInorder(curr.left);
console.log(`[${curr.data} `);
if (curr.random === undefined || curr.random === null)
console.log("NULL], ");
else
console.log(`${curr.random.data}], `);
printInorder(curr.right);
}
// This function clones the tree by copying the
// key (data) and left/right pointers.
function copyLeftRightNode(treeNode, mp) {
if (treeNode === null)
return null;
let cloneNode = new Node(treeNode.data);
// Store the mapping between original node and cloned
// node
mp.set(treeNode, cloneNode);
// Recursively clone the left and right subtrees
cloneNode.left
= copyLeftRightNode(treeNode.left, mp);
cloneNode.right
= copyLeftRightNode(treeNode.right, mp);
return cloneNode;
}
// This function copies the random pointers using
// the hashmap created in the previous step.
function copyRandom(treeNode, mp) {
if (treeNode === null)
return;
// Set the random pointer for the cloned node
mp.get(treeNode).random = mp.get(treeNode.random);
// Recursively copy random pointers for left and right
// subtrees
copyRandom(treeNode.left, mp);
copyRandom(treeNode.right, mp);
}
// This function creates the clone of the given binary tree.
function cloneTree(tree) {
if (tree === null)
return null;
// Create a hashmap to store the mapping
// between original and cloned nodes
let mp = new Map();
// Clone the tree structure (data, left, and right
// pointers)
let newTree = copyLeftRightNode(tree, mp);
// Copy the random pointers using the hashmap
copyRandom(tree, mp);
return newTree;
}
// Constructing the binary tree with random pointers
// Tree structure:
// 1
// / \
// 2 3
// / \
// 4 5
// Random pointers:
// 1 -> 5, 4 -> 1, 5 -> 3
let node = new Node(1);
node.left = new Node(2);
node.right = new Node(3);
node.left.left = new Node(4);
node.left.right = new Node(5);
node.random = node.left.right;
node.left.left.random = node;
node.left.right.random = node.right;
let clone = 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.
Clone a Binary Tree | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem