C语言 使用二叉搜索树查找数组中的最大整数,返回给出垃圾值



>我正在尝试从二叉搜索树中获取最大值。问题是"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 memoryn");
      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 %dn", 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 %dn",a); 
return 0;
} 

我需要你展示插入函数来准确回答。 但是,我相信问题是您在递归调用 getmax 时删除了返回值。尝试:

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

最新更新