Symmetric Trees in DAA

Symmetric Trees

The trees that are mirror images of themselves are known as symmetric trees.

Look at the following tree image below:

Symmetric Tree : Mirror Image of itself

The tree is symmetric as the left subtree is the mirror image of the right subtree.

The below tree is not an example of the symmetric tree as the left child of the left subtree is not equal to the right child of the right subtree.

Symmetric Tree : Mirror Image of itself

Let us now develop the algorithm to find whether the tree is symmetric or not. There are two methods recursive and iterative.

Method 1 (Iterative)

We need to identify if the left child of the left subtree is equal to the right child of the right subtree. For this check, we can take the help of queue data structure. Every time we will push each node in the queue and check for its equality. After that, we will pop it from the queue and push its left and right child if it exists and again compare for equality. The algorithm will traverse until we reach the leaf nodes.

Below is the implementation of method 1:

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // Creating a binary tree
 struct Node {
     int key; // The value of the node
     struct Node *left, *right; // The left and right pointers to the node
 };
 // Function to allocate memory to the new node
 Node* newNode(int key)
 {
     Node* temp = new Node;
     temp->key = key;
     temp->left = temp->right = NULL; // The child currently points to NULL
     return (temp);
 }
 //The function will return true if the tree is symmetric. Else, false
 bool isSymmetric(struct Node* root)
 {
     if (root == NULL) // If the tree has no node it is symmetric
         return true;
     // Case when exists only root node
     if (!root->left && !root->right) // If the left and right are NULL
         return true; // It is symmetric
     queue<Node*> q; // Creating a queue
     // We had pushed root two times in queue to check if there is only one child is alone or not
     q.push(root);
     q.push(root);
     // Two nodes for checking the symmetry
     Node *leftNode, *rightNode;
     while (!q.empty()) {     // Iterate in the queue
         // Remove the first two nodes to check symmetry
         leftNode = q.front(); // Taking that node
         q.pop(); // popping it from queue
         // The second node
         rightNode = q.front();
         q.pop();
         // Return false if the values are not same of leftNode and rightNode
         if (leftNode->key != rightNode->key) { /// Keys are not similar
             return false; // Not symmertic
         }
         // If the current nnode has children ie not null
         if (leftNode->left && rightNode->right) {
             q.push(leftNode->left); // push left child in queue
             q.push(rightNode->right); // push right child in queue
         }
         // if any one child is missing return false
         else if (leftNode->left || rightNode->right)
             return false;
         if (leftNode->right && rightNode->left) { // If both parent node exists
             q.push(leftNode->right); // push the right child in the queue
             q.push(rightNode->left); //push the left child in the queue
         }
           // Case of single child of a parent exists
              else if (leftNode->right || rightNode->left)
             return false;
     }
     return true;
 }
 // Main function
 int main()
 {
     // Construct the symmetric tree
     Node* root = newNode(1); // Root node
     root->left = newNode(2); // left of root
     root->right = newNode(2); // right of root
     root->left->left = newNode(3); // left child  of 2
     root->left->right = newNode(4); // right child of 2
     root->right->left = newNode(4); // left child of parent right 2
     root->right->right = newNode(3); // right child of parent right 2
     if (isSymmetric(root)) // call function isSymmetric
         cout << "The tree is Symmetric";
     else
         cout << "The tree is not Symmetric";
     return 0;
 } 

Output:

The given tree is Symmetric

Method 2 (Recursive)

This method takes a left and right of a level and checks at each stage if the left child is equal to the right child until it reaches the leaf nodes.

The below code shows recursive approach:

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 // Creating a binary tree
 struct Node {
     int key; // The value of the node
     struct Node *left, *right; // The left and right pointers to the node
 };
 // Function to allocate memory to the new node
 Node* newNode(int key)
 {
     Node* temp = new Node;
     temp->key = key; // Store the tree node value
     temp->left = temp->right = NULL; // The child currently points to NULL
     return (temp); // return current pointer of tree
 }
 // Passed two trees with roots as root1 and root2
 bool isMirror(struct Node* root1, struct Node* root2)
 {
           if (root1 == NULL && root2 == NULL) // If both of them are NULL
                    return true; // return true for being mirror images
           // If both root values exist and both root have equal root values
           // check for the left - right subtree and right - left subtree
           if (root1 && root2 && root1->key == root2->key)
                    return isMirror(root1->left, root2->right)
                              && isMirror(root1->right, root2->left); // It will call recursively
                    return false; // If both conditions are not satisfied
 }
 // The function gives true if symmetric else non symmetric return false
 bool isSymmetric(struct Node* root)
 {
           // The isMirror is a recursive function that sends root and root to check the
           // symmetric tree existence
           return isMirror(root, root);
 }
 // Main function
 int main()
 {
     // Construct the symmetric tree
     Node* root = newNode(1); // Root node
     root->left = newNode(2); // left of root
     root->right = newNode(2); // right of root
     root->left->left = newNode(3); // left child  of 2
     root->left->right = newNode(4); // right child of 2
     root->right->left = newNode(4); // left child of parent right 2
     root->right->right = newNode(3); // right child of parent right 2
     if (isSymmetric(root)) // call function isSymmetric
         cout << "The tree is Symmetric";
     else
         cout << "The tree is not Symmetric";
     return 0; // return from main
 } 

Output:

The tree is Symmetric

Related Topics

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 minutes read.

DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List We will sort a singly link list using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The insertion sort technique works...

3 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.