c - Printing Sums within range for a Binary Search Tree -
i've got code working, reason isn't taking values of each node , adding them up. instead, output sum 0 each time. thought sum = sum + data line in btreesumrange method take care of this. idea how fix this?
#include <stdio.h> #include <stdlib.h> static long long sum; typedef struct node { long long data; struct node *left; struct node *right; } node; node * btreeinsert(node *node,long long data) { if(node==null) { struct node *temp; temp = (struct node *)malloc(sizeof(node)); temp -> data = data; temp -> left = temp -> right = null; return temp; } if(data >(node->data)) { node->right = btreeinsert(node->right,data); } else if(data < (node->data)) { node->left = btreeinsert(node->left,data); } return node; } void btreesumrange(node *tree, long long min,long long max) { if (tree == null) { return; } btreesumrange(tree->left, min, max); long long data= tree->data; if((data>=min)&&(data<=max)){ sum = sum + data; } btreesumrange(tree->right, min, max); } int main() { node *root; long long value; root = null; file* data = fopen ("dataa", "r"); file* range = fopen ("rangea", "r"); while(fscanf(data, "%lld\n", &value) != eof){ printf("%lld\n", value); btreeinsert(root, value); } long long min; long long max; while(fscanf(range, "%lld %lld\n", &min, &max) != eof){ btreesumrange(root, min, max); printf("range [%lld,%lld]. sum = %lld. \n", min, max, sum); } return 0; }
you have 2 problems in code.
- at top level
root
not being set initial call ofbtreeinsert
.btreeinsert(root, value);
shouldroot = btreeinsert(root, value);
the malloc call using incorrect size:
temp = (struct node *)malloc(sizeof(node));
the confusion comes fact there both type named
node
, variable namednode
. , in line variable in scope. variable pointersizeof(node)
gives pointer size. want struct size not pointer size. suggest avoid such confusion in future not overloading type , variable names. 1 way fix change line following (no cast needed btw):temp = malloc(sizeof(*temp));
Comments
Post a Comment