Reputation: 31
I'm trying to get the maximum value from a binary search tree. The problem is that the "getmax" function is returning a garbage value to "max". What am I doing wrong here? If you see any error please let me know.
I haven't included the insert function here. Edit: here's the entire program.
#include <stdio.h>
#include <stdlib.h>
typedef struct mynode_tag
{
int index;
struct mynode_tag *right;
struct mynode_tag *left;
} mynode;
void insert(mynode **root, int index)
{
mynode *tmp;
if (*root == NULL)
{
tmp = malloc(sizeof(mynode));
if (tmp == NULL)
{
fprintf(stderr, "Unable to allocate memory\n");
return;
}
tmp->index = index;
*root = tmp;
}
else
{
if (index> (*root)->index)
{
insert(&(*root)->right, index);
}
else
{
insert(&(*root)->left,index);
}
}
}
int getmax(mynode * root)
{
if (root->right !=NULL)
{getmax(root->right);}
if (root->right == NULL)
{ printf("Root-index inside function %d\n", root->index); //gives the right value
return (root->index);}
}
int main (int argc, char * v[])
{
int index[6] = {0, 2, 9, 10, 3, 7};
int i;
int max;
mynode *root = NULL;
for (i=0; i<6; i++)
{
insert(&root, index[i]);
}
max = getmax(root);
printf("The largest number in the array is %d\n",a);
return 0;
}
Upvotes: 0
Views: 946
Reputation: 714
I need you to show the insert function to answer precisely. However, I believe that the problem is that you are dropping the returned value in recursive call to getmax. Try:
if (root->right !=NULL)
{
return ( getmax(root->right) );
}
Upvotes: 1