Symmetric Binary Tree

Each node has a left and a right subtree in a binary tree. Any binary tree, including empty, single-node trees, and subtrees, can exist. If the right subtree and the left subtree of the root node are mirror images of each other, then a binary tree is said to be symmetric.

Validate whether a binary tree is a mirror of itself if one is provided.

For illustration, the binary tree below is symmetric:

Symmetric Binary Tree

The goal is to create a recursive method called isMirror() that accepts two arguments of trees and returns true if the two trees are the mirror and false otherwise. Recursively examining two roots and subtrees beneath the root is the isMirror() method.

Approach:

The following is a concise summary of the algorithmic steps:

  • We start out with two variables, root1 and root2, both of which point to the root.
  • The nodes are then traversed using any tree traversal method. In this traversal function, we will simultaneously alter root1 and root2.
  • In the base scenario, we return true if both are referring to NULL, but we return false if just one is pointing to NULL and the other is pointing to a node.
  • We initially compare the values of any two points that point to the same node, and if they are equal, we look at the lower levels of the tree.
  • Recursively calling the function checks the left child of the root1 with the right child of the root2, and then checks the right child of the root1 with the left child once again.
  • We return true from our function if all three conditions-the node values of the left and right and the two recursive calls-are satisfied, otherwise we return false.

The aforesaid algorithm is implemented in the manner shown below.

C Program:

Output:

Symmetric

C++ Program:

Output:

Symmetric
  • Time Complexity: O(N)
  • Auxiliary Space: O(h), where h represents the tree's highest point.





Latest Courses