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 ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )