×

Symmetric binary tree

Implementation

// writing a C++ program to check whether a given binary tree is symmetric or not.
#include <bits/stdc++.h>
using namespace std;


// creating a binary tree node.
struct __Nod {
	int ky;
	struct __Nod *Lft, *Rt;
};


// creating a new utility function that will eventually help us in creating a new node. 
__Nod* new__Nod(int ky)
{
	__Nod* temp = new __Nod;
	temp->ky = ky;
	temp->Lft = temp->Rt = NILL;
	return (temp);
}


// this function will return the actual value if the given tree with the root nodes as root1 and root2 are their mirrors. 
bool isMirror(struct __Nod* root1, struct __Nod* root2)
{
	// In case both the trees are empty or vacant; they are mirror images of the same. 
	if (root1 == NILL && root2 == NILL)
		return true;


	//To be two trees to be identical or their mirror images then, the following conditions should be followed: - 
	// 1.) The key present in the root node should be the same. 
	// 2.) The left subtree of the left tree, along with the right subtree of the right tree, should be identical or mirror images. 
	// 3.) The right subtree of the left tree and the left subtree of the right tree should be mirror images of each other. 
	if (root1 && root2 && root1->ky == root2->ky)
		return isMirror(root1->Lft, root2->Rt)
			&& mirror(root1->Rt, root2->Lft);


	// If the above-given conditions don't match or give actual value, then root1 and 2 do not mirror images of each other.


	return false;
}


// We must return the actual value if the tree is symmetric or its mirror image. 
bool isSymmetric(struct __Nod* root)
{
	// Checking whether the tree is identical or not.
	return isMirror(root, root);
}


// writing the main code.
int main()
{
	__Nod* root = new__Nod(1);
	root->Lft = new__Nod(2);
	root->Rt = new__Nod(2);
	root->Lft->Lft = new__Nod(3);
	root->Lft->Rt = new__Nod(4);
	root->Rt->Lft = new__Nod(4);
	root->Rt->Rt = new__Nod(3);


	if (isSymmetric(root))
		cout << "Symmetric";
	else
		cout << "Not symmetric";
	return 0;
}

Output:

Symmetric binary tree

Example 2)

// writing a C program to check whether a given binary tree is symmetric or not.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// creating a binary tree node.
typedef struct __Nod {
	int ky;
	struct __Nod *Lft, *Rt;
} __Nod;
// creating a new utility function that will eventually help us in creating a new node. 
__Nod* new__Nod(int ky)
{
	__Nod* temp = (__Nod *)malloc(sizeof(__Nod));
	temp->ky = ky;
	temp->Lft = temp->Rt = NILL;
	return (temp);
}
// this function will return the actual value if the given tree with the root nodes as root1 and root2 are their mirrors. 
bool isMirror(__Nod* root1, __Nod* root2)
{
	// In case both the trees are empty or vacant; they are mirror images of the same. 
	if (root1 == NILL && root2 == NILL)
		return true;


	//To be two trees to be identical or their mirror images then, the following conditions should be followed: - 
// 1.) The key present in the root node should be the same. 
	// 2.) The left subtree of the left tree, along with the right subtree of the right tree, should be identical or mirror images. 
	// 3.) The right subtree of the left tree and the left subtree of the right tree should be mirror images of each other. 
	if (root1 && root2 && root1->ky == root2->ky)
		return isMirror(root1->Lft, root2->Rt)
			&& isMirror(root1->Rt, root2->Lft);


	// If the above-given conditions don't match or give actual value, then root1 and 2 do not mirror images of each other.
	return false;
}
// We must return the actual value if the tree is symmetric or its mirror image. 
bool isSymmetric(__Nod* root)
{
// Checking whether the tree is identical or not.
	return isMirror(root, root);
}
// writing the main code.
int main()
{
	__Nod* root = new__Nod(1);
	root->Lft = new__Nod(2);
	root->Rt = new__Nod(2);
	root->Lft->Lft = new__Nod(3);
	root->Lft->Rt = new__Nod(4);
	root->Rt->Lft = new__Nod(4);
	root->Rt->Rt = new__Nod(3);


	if (isSymmetric(root))
		printf("Symmetric");
	else
		printf("Not symmetric");
	return 0;
}

Output:

Symmetric binary tree

Example 3)

// Java program to check if a binary tree is symmetric or not
class __Nod {
	int ky;
	__Nod Lft, Rt;
	__Nod(int item)
	{
		ky = item;
		Lft = Rt = NILL;
	}
}


class BinaryTree {
	__Nod root;


	// returns true if trees with roots as root1 and
	// root2 are mirror
	boolean mirror(__Nod __Nod1, __Nod __Nod2)
	{
		// if both trees are empty, then they are the mirror image
		if (__Nod1 == NILL && __Nod2 == NILL)
			return true;


		// For two trees to be mirror images, the following
		// three conditions must be true
		// 1.) Their root __Nod's key must be the same
		// 2.) The left subtree of the left tree and the right subtree
		// of Rt tree have to be mirror images
		// 3.) Rt subtree of Lft tree and Lft subtree
		// of Rt tree have to be mirror images
		if (__Nod1 != NILL && __Nod2 != NILL
			&& __Nod1.ky == __Nod2.ky)
			return (isMirror(__Nod1.Lft, __Nod2.Rt)
					&& isMirror(__Nod1.Rt, __Nod2.Lft));


		// if none of the above conditions is true, then
		// root1 and root2 are not mirror images
		return false;
	}


	// returns true if the tree is symmetric i.e
	// mirror image of itself
	boolean isSymmetric()
	{
		// check if the tree is a mirror of itself
		return isMirror(root, root);
	}


	// Driver code
	public static void main(String args[])
	{
		BinaryTree tree = new BinaryTree();
		tree.root = new __Nod(1);
		tree.root.Lft = new __Nod(2);
		tree.root.Rt = new __Nod(2);
		tree.root.Lft.Lft = new __Nod(3);
		tree.root.Lft.Rt = new __Nod(4);
		tree.root.Rt.Lft = new __Nod(4);
		tree.root.Rt.Rt = new __Nod(3);
		boolean output = tree.isSymmetric();
		if (output == true)
			System.out.println("Symmetric");
		else
			System.out.println("Not symmetric");
	}
}

Output:

Symmetric binary tree

Related Topics

Height of a binary tree

The height of a binary tree is generally defined as the height or length of the root _nod in the entire binary tree. In simple words, the height of a...

4 minutes read.

Digital Search Tree in Data Structures

What is a digital search Tree in Data Structures? The Digital search tree is known for its application and diversity in the way it has impacted our world in the field...

3 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the...

3 minutes read.

Why is Binary Heap Preferred over BST for Priority Queue

A priority queue is a linear and ordered collection of elements in which each element has an attribute named priority and the priority attribute decides the order in which elements...

2 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

B Tree vs B + Tree: Data Structure

Difference Between B Tree and B+ Tree What is B Tree? B-Tree is a self-balancing or special type of m-way tree. B-Trees are used mainly in disc access. If we want...

3 minutes read.

Bubble Sort in Data Structures

Bubble Sort in C++ The bubble sort algorithm analyses two adjacent elements and swaps them until they are no longer in the desired order. Each iteration moves each member of the array...

4 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Deque in Data Structure

Deque A deque referred as “Double-Ended Queue”, is a linear collection of data items same like queue data structure. deque has two ends, front end and rear end, deque is the...

27 minutes read.

Introduction to 1D-Arrays

One Dimensional Array Technical Definitions The simplest version of an Array is a One-Dimensional Array, in which the items are stored linearly and may be accessed individually by supplying the index value...

6 minutes read.

Rearrange a linked list into alternate fashion first and the last element

Rearrange a linked list into alternate fashion first and the last element This article will explain how to rearrange the linked list into alternate fashion first and the last element. Here,...

3 minutes read.

What Is Dfs Algorithm in Data Structures

DFS stands for Depth First Search. Generally, it is a repetitive or decidable type of algorithm which is basically used in identifying all the vertices or nodes of a graph...

5 minutes read.

B Tree in Data Structure

Data management is called database management. A data model is a system that stores, manages, and optimizes computer resources. Data processing is not just about data storage. Almost every app...

9 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Insertion sort

Insertion sort is a simple sorting technique. It is best suited for small data sets, but it does not suitable for large data sets. In this technique, we pick an...

4 minutes read.

Deletion in B+ Tree

Make a search for the leaf node that containing the key value by taking the value in a key value. If the required key value is found, then it will remove...

6 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

String Operations in Data Structures

Operations on Strings Reversing the order of words in a sentence Reversing a string is a technique that reverses or alters the order of a given string so that the last character...

9 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 minutes read.