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

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

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 )