c++ - 我正在尝试使用此代码查找二叉树的高度,但它始终返回0,有人可以告诉我为什么吗?

标签 c++ algorithm binary-tree

我正在尝试使用此代码查找二叉树的高度,但它始终返回0,有人可以告诉我为什么吗?

int heightHelper(Node* root, int maxheight, int rootheight)
{

    if (root->right == nullptr && root->left == nullptr) { //checks if the node has a child
        if (maxheight < rootheight) {
            maxheight = rootheight;
        }
    }
    else { //if it has then increase height by 1
        rootheight += 1;

        if (root->left != nullptr) {
            heightHelper(root->left, maxheight, rootheight);
        }
        if (root->right != nullptr) {
            heightHelper(root->right, maxheight, rootheight);
        }
    }

    return maxheight; //return height
}

int height(Node* root)
{
    // Write your code here.

    return heightHelper(root, 0, 0); //root node base case
}

最佳答案

您正在混淆两种处理方式。使用指针或地址(int*&maxheight)传递结果参数。在这种情况下,没有返回值。但是,这是一种编码风格,我主要只在硬件编程中才能看到。

否则,您可以返回结果。您已经有一个返回参数,只需修正该值的实际用法即可,因为您的代码将忽略它。

这是两种方法:

使用返回参数:

int heightHelper(Node* root, int height)
{

    if (root->right == nullptr && root->left == nullptr) { //checks if the node has a child
        return height;
    }
    else { //if it has then increase height by 1
        height += 1;
        int maxheight1;
        int maxheight2;

        if (root->left != nullptr) {
            maxheight1 = heightHelper(root->left, height);
        }
        if (root->right != nullptr) {
            maxheight2 = heightHelper(root->right, height);
        }

        // return maximum of the two
        if (maxheight1 > maxheight2) return maxheight1;
        else return maxheight2;
    }
}

int height(Node* root)
{
    // Write your code here.

    return heightHelper(root, height); //root node base case
}

使用指针参数。请注意,rootheight对于每个分支都是局部的,因此请勿将其作为指针传递。
void heightHelper(Node* root, int* maxheight_ptr, int rootheight)
    {

    if (root->right == nullptr && root->left == nullptr) { //checks if the node has a child
        if (*maxheight < rootheight) {
            *maxheight = rootheight;
        }
    }
    else { //if it has then increase height by 1
        rootheight += 1;

        if (root->left != nullptr) {
            heightHelper(root->left, maxheight_ptr, rootheight);
        }
        if (root->right != nullptr) {
            heightHelper(root->right, maxheight_ptr, rootheight);
        }
    }
}

int height(Node* root)
{
    // Write your code here.

    int maxheight = 0;


    heightHelper(root, &maxheight, 0); //pass the addresses of variables

    return maxheight;
}

关于c++ - 我正在尝试使用此代码查找二叉树的高度,但它始终返回0,有人可以告诉我为什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59924994/

相关文章:

c - 搜索二叉搜索树的最有效方法是什么?

c++ - 当我因为模板而无法使用纯虚函数时简化类设计

c++ - 从 cpp 文件创建头文件 .h

c++ - 调用 new(堆)后意外的汇编程序代码抛出异常

java - 比较两个数组列表以保留它们之间的增量的有效方法

java - 恒定时间/空间复杂度概念的混淆

c++ - 如何使用 C++11 对 Arduino 进行编程?

algorithm - 如何选择一支富有生产力的员工队伍?

prolog - 使用 Prolog 获取所有可能的二叉树?

tree - 在二叉树中查找距给定节点最近的叶节点