Solution Review: Copy Tree

Let’s take a detailed look at the previous challenge’s solution.

Solution

The copy of a tree is generated by copying the nodes of the input tree at each level of traversal to the output tree. At each level of traversal, a new node is created and in this node, the value of the input tree node is copied. The left subtree is copied recursively and then a pointer to a new subtree is returned, which is then assigned to the left child pointer of the current new node. Similarly, this process is followed for the right subtree. This way, the tree is copied at the end.

Solution code

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.