How do you make a copy of a binary tree? Copying the root pointer is not enough: you get a second name for the same nodes, not a second tree. This page shows the difference, then steps through a recursive cloneBST that builds a real copy, one node at a time.
A tree is reached through one pointer to its root. If you write Node* copy = root;, you copy that one pointer. Now root and copy point to the same nodes. This is a shallow copy: change a value through one name and the other sees the change, and delete the tree through one name and the other is left pointing at freed memory.
A deep copy, or clone, makes a brand-new node for every node in the original, with the same keys and the same shape. Afterwards the two trees share nothing, so either one can be changed or deleted without affecting the other.
Node* copy = root;, the program calls a function that deletes every node of root. What happens if it then prints copy->key?copy still holds the address of the old root, but that memory has been freed. It is a dangling pointer. Reading through it is undefined behavior: it might print garbage, print the old value by luck, or crash.
A tree is a node plus a left subtree plus a right subtree, so a copy of a tree is a copy of the node plus copies of its two subtrees. That definition turns straight into code:
nullptr.The new node is created before its subtrees are copied, so this is a preorder traversal of the original.
// Function to clone a BST
Node* cloneBST(Node* root) {
if (root == nullptr) {
return nullptr;
}
// Create a new node with the same key as the root
Node* clonedNode = new Node(root->key);
// Recursively clone the left and right subtrees
clonedNode->left = cloneBST(root->left);
clonedNode->right = cloneBST(root->right);
return clonedNode;
}
// Usage
Node* copy = cloneBST(root);
cloneBST, but does it only work on binary search trees?No. It never compares keys; it only copies them and the shape. It clones any binary tree. On a BST the copy is also a BST, because it has exactly the same keys in exactly the same places.
new run when cloning a tree of n nodes? How many calls to cloneBST are made in total?new runs exactly n times, once per node. There are 2n + 1 calls in all: one per node plus one for each of the n + 1 null child pointers, which are the base cases.
Press Deep clone to step through cloneBST. Then click a node in the original and change it: the clone does not change. Try Shallow copy to see what happens when only the pointer is copied. The small number under each node is its (made-up) memory address.
root → copy → In this code it is natural, because the recursive results are stored straight into clonedNode->left and clonedNode->right, and that node must exist first. A postorder version also works if you clone both subtrees into local variables first and then build the node with them, but either way every node is created exactly once.
After a deep clone only the original changes; the clone still says 30. After a shallow copy both "trees" show 35, because there is only one tree. Try it with the buttons above.
Walk both trees together: they match if both are empty, or if both roots have the same key and their left subtrees match and their right subtrees match. Also check that no node of the clone has the same address as a node of the original, or it is not really a copy. The Check: identical? button runs this test.
Time: O(n). Each node is visited once and does a constant amount of work: one new and two assignments.
Extra space: O(n) for the copy, of course, plus O(h) for the recursion stack, where h is the height. That is O(log n) for a balanced tree but O(n) for a skewed one; try the Skewed preset and watch how deep the call stack gets.
Deleting a tree. Every new needs a delete, so a program that clones trees must also free them. Here the order is postorder: both subtrees must be freed before the node, because once the node is gone its child pointers can no longer be followed.
Mirror clone. Swap the two recursive calls and the copy comes out as a mirror image: left and right reversed at every node. Press Mirror clone above.
Same tree? Two trees are identical when both are empty, or when their roots have equal keys and both pairs of subtrees are identical.
void deleteTree(Node* root) {
if (root == nullptr) return;
deleteTree(root->left); // free the children first
deleteTree(root->right);
delete root; // then the node itself
}
Node* mirrorClone(Node* root) {
if (root == nullptr) return nullptr;
Node* m = new Node(root->key);
m->left = mirrorClone(root->right); // sides swapped
m->right = mirrorClone(root->left);
return m;
}
bool sameTree(Node* a, Node* b) {
if (a == nullptr || b == nullptr) return a == b;
return a->key == b->key
&& sameTree(a->left, b->left)
&& sameTree(a->right, b->right);
}
It is the original's inorder sequence reversed. Mirroring swaps "left subtree, node, right subtree" into "right subtree, node, left subtree" at every level. For a BST, the mirror's inorder comes out in decreasing order.
Yes, with an explicit stack or a queue that holds pairs (original node, its copy). Pop a pair, create copies of the original's children, link them to the copy, and push the new pairs. It does the same work; recursion just keeps that stack for you.