Answers for "mirror binary tree"

C++
0

mirror a binary tree

//mirror a binary tree 

void mirror(Node root){
Queue<Node> q=new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
Node currnode=q.poll();
Node temp=currnode.left;
currnode.left=currnode.right;
currnode.right=temp;
if(currnode.left!=null){
q.add(currnode.left);
}
if(currnode.right!=null){
q.add(currnode.right);
}
}
}
Posted by: Guest on September-29-2020
0

mirror binary tree

//Program in C++ to check wheather a binary tree is a mirror 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