Check whether a binary tree is a complete tree or not
PROBLEM :
Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not.
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. See following examples.
The following trees are examples of Complete Binary Trees
1
/ \
2 3
1
/ \
2 3
/
4
1
/ \
2 3
/ \ /
4 5 6
The following trees are examples of Non-Complete Binary Trees
1
\
3
1
/ \
2 3
\ / \
4 5 6
1
/ \
2 3
/ \
4 5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;---------------------------------------------*/
int size_tree(tree* ) ;
int Complete_Btree(tree *,int ,int ) ;
int check_Complete_Btree(tree *root)
{
int s,i ;
s=size_tree(root) ;
i=0 ;
return Complete_Btree(root,i,s) ;
}
int size_tree(tree* root)
{
if(root==NULL)
return 0 ;
return ((size_tree(root->left))+(size_tree(root->right))+1) ;
}
int Complete_Btree(tree *root,int k,int size)
{
if(root==NULL)
return 1 ;
if(k>=size)
return 0 ;
return (Complete_Btree(root->left,2*k+1,size)&&Complete_Btree(root->right,2*k+2,size)) ;
}
---------------------------------------------------------------------------------
Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not.
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. See following examples.
The following trees are examples of Complete Binary Trees
1
/ \
2 3
1
/ \
2 3
/
4
1
/ \
2 3
/ \ /
4 5 6
The following trees are examples of Non-Complete Binary Trees
1
\
3
1
/ \
2 3
\ / \
4 5 6
1
/ \
2 3
/ \
4 5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;---------------------------------------------*/
int size_tree(tree* ) ;
int Complete_Btree(tree *,int ,int ) ;
int check_Complete_Btree(tree *root)
{
int s,i ;
s=size_tree(root) ;
i=0 ;
return Complete_Btree(root,i,s) ;
}
int size_tree(tree* root)
{
if(root==NULL)
return 0 ;
return ((size_tree(root->left))+(size_tree(root->right))+1) ;
}
int Complete_Btree(tree *root,int k,int size)
{
if(root==NULL)
return 1 ;
if(k>=size)
return 0 ;
return (Complete_Btree(root->left,2*k+1,size)&&Complete_Btree(root->right,2*k+2,size)) ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment