c++ - 二叉搜索树错误

标签 c++ tree

我想在二叉搜索树中找到最小值。 我写了下面的代码。但是当我从 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/

相关文章:

java - 在Java中遍历一棵树

java - 如何找到可能的二叉树拓扑排列的数量?

c++ - 我如何使用 C++ 获得微秒和纳秒的两个时间间隔之间的差异

c++ - 如何给模板类添加常用功能?

c++ - 如何使用基类指针引用派生类成员?

C++结构二维字符串成员初始化

c++ - 为什么要定义一个返回结构的 lambda 函数而不是直接定义结构?

java - DFS 一棵没有内存的树

graph - 需要 BFS、DFS 搜索将树标记为已访问?

python - 计算任意(非二叉)树的高度