Data Structures · Trees

Cloning a binary tree

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 pointer copy is not a tree copy

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.

Shallow vs deep. Left: two pointers, one tree. Right: two pointers, two separate trees with the same keys.
Stop and think
After 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.

The recursive clone

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:

  1. Base case: the copy of an empty tree is an empty tree, so return nullptr.
  2. Copy the node: make a new node with the same key.
  3. Copy the subtrees: clone the left subtree and attach it as the new node's left child; do the same on the right.
  4. Return the new node, the root of the copy.

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);
Stop and think
The function says 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.

How many times does 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.

Watch it run

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.

Original
root →
copy →
Edit the original:

Call stack

    What is happening

    clone.cpp

      Stop and think
      Why must the new node be created before its subtrees are cloned (preorder), rather than after (postorder)?

      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.

      You change 30 to 35 in the original after a deep clone. Which tree changes? What if it was a shallow copy?

      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.

      How could a program check that a clone is correct?

      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.

      Cost

      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.

      Related recursions

      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);
      }
      Stop and think
      What is the inorder traversal of a mirror clone, compared with the original's?

      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.

      Could you clone a tree without recursion?

      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.