check if binary tree is symmetric tree

Solutions on MaxInterview for check if binary tree is symmetric tree by the best coders in the world

showing results for - "check if binary tree is symmetric tree"
Allan
06 Jan 2019
1//Program in C++ to check wheather a binary tree is a mirror/symmetric tree or not
2
3//A binary tree is a mirror tree when it is foldable i.e it's left side and right side nodes will fall on each other when
4//folded by drawing a line b/w it vertically
5
6#include <iostream>
7using namespace std;
8
9struct btree{
10    btree *left,*right;
11    int data;
12    btree(int val){
13        left = right = NULL;
14        data = val;
15    }
16};
17
18bool checkMirror(btree *a,btree *b){
19    //if both the nodes 
20  	if(!a && !b)
21        return true;
22    
23    if(!a || !b || a->data != b->data)
24        return false;
25    
26    return checkMirror(a->left,b->right) && checkMirror(a->right,b->left);
27}
28
29bool isMirror(btree *root){
30    if(!root) return true;
31    
32    return checkMirror(root->left,root->right);
33}
34
35int main() {
36	btree *root        = new btree(1); 
37    root->left        = new btree(2); 
38    root->right       = new btree(2); 
39    root->left->left  = new btree(3); 
40    root->left->right = new btree(4); 
41    root->right->left  = new btree(4); 
42    root->right->right = new btree(3);
43    
44    if(isMirror(root))
45    cout<<"yes";
46    else
47    cout<<"no";
48	return 0;
49}