【问题标题】:Finding the maximum integer in an array using binary search tree, return giving garbage value使用二叉搜索树查找数组中的最大整数,返回垃圾值
【发布时间】:2013-10-31 04:14:32
【问题描述】:

我正在尝试从二叉搜索树中获取最大值。问题是“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;
} 

【问题讨论】:

  • 开启编译器警告。

标签: c struct linked-list binary-search-tree


【解决方案1】:

我需要你显示插入功能才能准确回答。但是,我认为问题在于您在对 getmax 的递归调用中删除了返回值。 试试:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多