C Program to Find Sum of Odd Elements in BST
#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *create(struct node *root, int d)
{
struct node *n = (struct node *)malloc(sizeof(struct node));
n->data = d;
n->left = NULL;
n->right = NULL;
if (root == NULL)
{
root = n;
return root;
}
if (d <= (root)->data)
{
root->left = create(root->left, d);
}
else
{
root->right = create(root->right, d);
}
return root;
}
int s = 0;
int oddsum(struct node *root)
{
if (root != NULL)
{
int s1 = oddsum(root->left);
if (root->data % 2 == 1)
{
s += root->data;
}
int s2 = oddsum(root->right);
return s;
}
}
int main()
{
struct node *root = NULL;
root = create(root, 5);
create(root, 4);
create(root, 2);
create(root, 9);
create(root, 7);
create(root, 1);
create(root, 3);
printf("%d", oddsum(root));
return 0;
}Output
25
Post a Comment
If you have any doubts, please let me know