Given a binary tree, write an efficient algorithm to determine if it can be converted into another binary tree by doing any number of swaps of its right and left branches.

For example, consider a binary tree shown on the left below. It can be converted into a binary tree shown on the right by few swaps of its right and left branches.

Swap Binary Tree Nodes
 

Practice this problem

We can easily solve this problem by using recursion. We return true if:

  1. Both trees are the same, or both trees are empty, or
  2. Both trees are non-empty, the value of the root of X and Y are the same, and either of the following conditions are satisfied:
    1. The left subtree of X can be converted into the left subtree of Y, and the right subtree of X can be converted into the right subtree of Y.
    2. The right subtree of X can be converted into the left subtree of Y, and the left subtree of X can be converted into the right subtree of Y.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Binary tree can be converted

Java


Download  Run Code

Output:

Binary tree can be converted

Python


Download  Run Code

Output:

Binary tree can be converted

The time complexity of the above solution is O(n2), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.