Foldable Binary Trees
PROBLEM :
Question: Given a binary tree, find out if the tree can be folded or not.
A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each other. An empty tree is considered as foldable.
Consider the below trees:
(a) and (b) can be folded.
(c) and (d) cannot be folded.
(a)
10
/ \
7 15
\ /
9 11
(b)
10
/ \
7 15
/ \
9 11
(c)
10
/ \
7 15
/ /
5 11
(d)
10
/ \
7 15
/ \ /
9 10 12
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;------------------------------*/
int foldable_tree(tree *root)
{
if(root==NULL)
return 1 ;
int check=check_foldable(root->left,root->right) ;
return check ;
}
int check_foldable(tree *Ltree,tree *Rtree)
{
if(Ltree==NULL&&Rtree==NULL)
return 1 ;
if(Ltree==NULL&&Rtree!=NULL)
return 0 ;
if(Ltree!=NULL&&Rtree==NULL)
return 0 ;
return ( check_foldable(Ltree->left,Rtree->right) && check_foldable(Rtree->left,Rtree->left) );
}
---------------------------------------------------------------------------------
Question: Given a binary tree, find out if the tree can be folded or not.
A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each other. An empty tree is considered as foldable.
Consider the below trees:
(a) and (b) can be folded.
(c) and (d) cannot be folded.
(a)
10
/ \
7 15
\ /
9 11
(b)
10
/ \
7 15
/ \
9 11
(c)
10
/ \
7 15
/ /
5 11
(d)
10
/ \
7 15
/ \ /
9 10 12
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;------------------------------*/
int foldable_tree(tree *root)
{
if(root==NULL)
return 1 ;
int check=check_foldable(root->left,root->right) ;
return check ;
}
int check_foldable(tree *Ltree,tree *Rtree)
{
if(Ltree==NULL&&Rtree==NULL)
return 1 ;
if(Ltree==NULL&&Rtree!=NULL)
return 0 ;
if(Ltree!=NULL&&Rtree==NULL)
return 0 ;
return ( check_foldable(Ltree->left,Rtree->right) && check_foldable(Rtree->left,Rtree->left) );
}
---------------------------------------------------------------------------------
Comments
Post a Comment