How to Copy a Binary Tree in Python

In this tutorial, we explain how to copy a binary tree in Python using a simple recursive method. A binary tree is a data structure in which every node has at most two children, called the left child and the right child.

We aim to create a duplicate of the provided binary tree, where each node in the original tree corresponds to a new node in the copy with the same value.

Step 1: Define a Node class

Let’s start by defining a Node class which represents a node in the binary tree. Each Node instance contains a value, in addition to pointers to its left and right children, if they exist.

Step 2: Define the recursive copy function

We now need to define a function to recursively copy each node in the binary tree. For each node, we create a new Node instance with the same value and recursively copy the left and right children.

Step 3: Usage

Now you can create a binary tree and copy it using the functions we have defined.

Full Code

Here is the complete Python code:

<__main__.Node object at 0x0000023A23CDED10>
<__main__.Node object at 0x0000023A23CDEF10>

Conclusion

It’s critical to understand that the duplicate binary tree and the original binary tree are two separate entities, even though their structures and node values are identical. Modifying one tree will not affect the other. This is useful in many contexts, when you may need to manipulate or transform a binary tree without changing the original data.