我正在尝试从二进制搜索树中获取最大值。问题是“ getmax”函数将垃圾值返回到“ max”。我在这里做错了什么?如果您发现任何错误,请告诉我。

我没有在这里包括插入功能。
编辑:这是整个程序。

#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;
}

最佳答案

我需要您显示插入函数以准确回答。但是,我认为问题在于您正在递归调用getmax时丢弃返回的值。
尝试:

if (root->right !=NULL)
{
     return ( getmax(root->right) );
}

09-10 03:15
查看更多