Monday, 4 September 2017

Write a program to build a complete binary tree and to chek if it satisfies the child sum property.

#include<stdio.h>
#include<stdlib.h>

int * createCompleteBinaryTree(int n);
void printCompleteBinaryTree(int * tree, int n);
int isSumProperty(int * tree, int n);

int main()
{
    int n, * tree;
    printf("Enter the number of elements in the tree\n");
    scanf("%d",&n);
    tree = createCompleteBinaryTree(n);
    printCompleteBinaryTree(tree,n);
    if(isSumProperty(tree,n))
        printf("The tree satisfies the children sum property\n");
    else
        printf("The tree does not satisfy the children sum property\n");
    return 0;
}

int * createCompleteBinaryTree(int n)
{
    int i;
    int * tree = (int *) malloc(n*sizeof(int));
    printf("Enter the elements in the tree\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",(tree+i));
    }
    return tree;
}


void printCompleteBinaryTree(int * tree, int n)
{
    int i;
    printf("The elements in the tree in level order are");
    for(i=0;i<n;i++)
        printf(" %d",*(tree+i));
    printf("\n");
}

int isSumProperty(int * tree, int n)
{
int i,j=1,sum=0;
n=n/2;
for(i=0;i<n;i++)
{
    sum=*(tree+i);
    if(sum!=*(tree+j)+*(tree+j+1))
    return 0;
    else
    j=j+2;
   
}
return 1;
}


No comments:

Post a Comment