Given a binary tree, write an efficient algorithm to check if it has a symmetric structure or not, i.e., left and right subtree mirror each other.

For example, the following are some binary trees that have a symmetric structure:

 
Symmetric Binary Tree

Practice this problem

The tree has a symmetric structure if the left and right subtree mirror each other. Two trees mirror each other if all the following conditions are satisfied:

  • Both trees are empty, or both are non-empty.
  • The left subtree is the mirror of the right subtree.
  • The right subtree is the mirror of the left subtree.

We can quickly check this using recursion. Following is the implementation of the idea in C++, Java, and Python:

C++


Download  Run Code

Output:

The binary tree is symmetric

Java


Download  Run Code

Output:

The binary tree is symmetric

Python


Download  Run Code

Output:

The binary tree is symmetric

The time complexity of the above solution is O(n), 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.

Alternate Approach

We can also check for symmetric structure by converting either the left subtree or the right subtree to their mirror and then check if both left and right subtrees have identical structures or not. The time complexity of this approach remains O(n), but it modifies the tree structure. We can restore the tree to its original structure by again taking a mirror of the corresponding left or right subtree.

 
Exercise: Extend the solution to check for symmetric content along with symmetric structure.