Symmetric Tree (Mirror Image of itself)
PROBLEM :
Given a binary tree, check whether it is a mirror of itself.
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;---------------------------------------------*/
// same root is send as argument twice
// Symmetric_Tree(root,root) ;
int Symmetric_Tree(tree *root1,tree *root2)
{
if(root1==NULL&&root2==NULL)
return 1 ;
if(root1->info==root2->info)
return (Symmetric_Tree(root1->left,root2->right)&&Symmetric_Tree(root1->right,root2->left)) ;
return 0 ;
}
---------------------------------------------------------------------------------
Given a binary tree, check whether it is a mirror of itself.
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;---------------------------------------------*/
// same root is send as argument twice
// Symmetric_Tree(root,root) ;
int Symmetric_Tree(tree *root1,tree *root2)
{
if(root1==NULL&&root2==NULL)
return 1 ;
if(root1->info==root2->info)
return (Symmetric_Tree(root1->left,root2->right)&&Symmetric_Tree(root1->right,root2->left)) ;
return 0 ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment