我想在二叉搜索树中找到最小值。 我写了下面的代码。但是当我从 main 调用该函数并打印返回值时,它始终打印为 0。
请你帮忙。
int findMinimumValue(struct tnode* node)
{
int min=node->data;
if(node->lchild==NULL)
{
return min;
}
else
findMinimumValue(node->lchild);
}
最佳答案
看起来您实际上并没有返回递归调用的值:
int findMinimumValue(struct tnode* node)
{
int min=node->data;
if(node->lchild==NULL)
{
return min;
}
else
{
// you need the return here or you're never returning
// anything in this branch
return findMinimumValue(node->lchild);
}
}
就此而言,实际上对变量的需求并不多,那么:
int findMinimumValue(struct tnode* node)
{
if (node->lchild == NULL)
return node->data;
else
return findMinimumValue(node->lchild);
}
哦,顺便提一句:我会考虑改用它的非递归版本;这也很简单:
int findMinimumValue(struct tnode* node)
{
while (node->lchild != NULL)
node = node->lchild;
return node->data;
}
关于c++ - 二叉搜索树错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7137848/