我想在二进制搜索树中找到最小值.我写了下面的代码.但是当我从main调用函数并且我返回值时,它总是打印为0.
请你帮忙.
int findMinimumValue(struct tnode* node)
{
int min=node->data;
if(node->lchild==NULL)
{
return min;
}
else
findMinimumValue(node->lchild);
}
Run Code Online (Sandbox Code Playgroud)
看起来你实际上没有返回递归调用的值:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
对于这个问题并不是真的需要变量,它是什么,怎么样:
int findMinimumValue(struct tnode* node)
{
if (node->lchild == NULL)
return node->data;
else
return findMinimumValue(node->lchild);
}
Run Code Online (Sandbox Code Playgroud)
哦,就像提一样:我会考虑使用非递归版本; 它也很简单:
int findMinimumValue(struct tnode* node)
{
while (node->lchild != NULL)
node = node->lchild;
return node->data;
}
Run Code Online (Sandbox Code Playgroud)