Answers for "check-if-binary-tree-is-symmetric-tree"

C++
0

check-if-binary-tree-is-symmetric-tree

//Program in C++ to check wheather a binary tree is a mirror/symmetric tree or not

//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
//folded by drawing a line b/w it vertically

#include <iostream>
using namespace std;

struct btree{
    btree *left,*right;
    int data;
    btree(int val){
        left = right = NULL;
        data = val;
    }
};

bool checkMirror(btree *a,btree *b){
    //if both the nodes 
  	if(!a && !b)
        return true;
    
    if(!a || !b || a->data != b->data)
        return false;
    
    return checkMirror(a->left,b->right) && checkMirror(a->right,b->left);
}

bool isMirror(btree *root){
    if(!root) return true;
    
    return checkMirror(root->left,root->right);
}

int main() {
	btree *root        = new btree(1); 
    root->left        = new btree(2); 
    root->right       = new btree(2); 
    root->left->left  = new btree(3); 
    root->left->right = new btree(4); 
    root->right->left  = new btree(4); 
    root->right->right = new btree(3);
    
    if(isMirror(root))
    cout<<"yes";
    else
    cout<<"no";
	return 0;
}
Posted by: Guest on October-04-2021

Browse Popular Code Answers by Language