2011-08-21 150 views
0

我想在二叉搜索树中找到最小值。我写了下面的代码。但是,当我从main调用函数并且pribt返回值时,它始终打印为0。二进制搜索树错误

cal请你帮忙。

int findMinimumValue(struct tnode* node) 
{ 
int min=node->data; 
if(node->lchild==NULL) 
{ 
    return min; 
} 
else 
    findMinimumValue(node->lchild); 
} 
+0

这是什么语言? (请适当地标记问题。)你有没有试图调试这个? –

+2

如果你调高了编译器的警告级别,你会立即发现问题。 –

+0

我在运行和编译代码时没有收到任何错误。 – aj983

回答

6

你好像没有真正给您回电话递归的价值:

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; 
} 
+0

bleah,写回答太晚不得不编辑两次,因为不知何故,我从“没有在这个分支返回“键入”min =“。在两个地方。 – shelleybutterfly

+0

谢谢。现在它工作了。这是我身边的一个愚蠢的错误。递归中有很多问题。你可以请建议一些教程链接ets来改进概念。 – aj983

+0

:)我一直在那里,不用担心。递归可能很难。至于教程,一个快速的谷歌翻了这个,它似乎很酷:http://erwnerve.tripod.com/prog/recursion/ – shelleybutterfly