Check for Children-Sum property in Binary Tree in C

Children-Sum property in Binary Tree

 

Children-Sum property says that for each node sum of its left and right children should be equal to node value.

Also, following assumptions are to be kept in mind while recursively traversing tree

  1. A leaf node satisfies children sum property because leaf nodes don’t have any child nodes.
  2. An Empty tree satisfies Children sum property.
children sum property

Algorithm :

 

  • Traverse the tree.

  • For every node in tree check whether the value in root node equals the sum of its leftchild and rightchild.

  • If yes continue from Step 1 Until, root becomes Null i.e,  root==NULL

  • If No return 0.

children sum property in C

Code in C based on above Algorithm

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

struct node
{
int data;
struct node* left;
struct node* right;
};

int isSumProperty(struct node* node)
{
int left_data = 0, right_data = 0;

if(node == NULL || (node->left == NULL && node->right == NULL))
return 1;
else
{
if(node->left != NULL)
left_data = node->left->data;

if(node->right != NULL)
right_data = node->right->data;

if((node->data == left_data + right_data)&&isSumProperty(node->left) && isSumProperty(node->right))
return 1;
else
return 0;
}
}

struct node* newNode(int data)
{
struct node* node =(struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}

int main()
{
struct node *root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->right = newNode(2);
if(isSumProperty(root))
printf("The given tree satisfies the children sum property ");
else
printf("The given tree does not satisfy the children sum property ");

getchar();
return 0;
}
Output :


The given tree satisfies the children sum property