【问题标题】:error: return-statement with no value, in function returning 'int' [-fpermissive] [closed]错误:没有值的返回语句,在返回'int'的函数中[-fpermissive] [关闭]
【发布时间】:2021-06-01 15:02:05
【问题描述】:

我已经在 C++ 中编写了二叉树遍历及其高度,但是在经过一些编码后编译但我不断收到错误:Return Statement with no value, in function return 'int' (-fpermissive)。

这是我的代码:

#include <bits/stdc++.h>
using namespace std;

struct node
{
    int data;
    struct node *right;
    struct node *left;

    node(int val)
    {
        data = val;
        left = NULL;
        right = NULL;
    }
};

void Preorder(struct node *root)
{
    if (root == NULL)
    {
        return;
    }

    cout << root->data << " ";
    Preorder(root->left);
    Preorder(root->right);
}

void Postorder(struct node *root)
{
    if (root == NULL)
    {
        return;
    }

    cout << root->data << " ";
    Postorder(root->left);
    Postorder(root->right);
}

void Inorder(struct node *root)
{
    if (root == NULL)
    {
        return;
    }

    cout << root->data << " ";
    Inorder(root->left);
    Inorder(root->right);
}

int Height(node *root)
{
    if (root == NULL)
    {
        return;
    }

    int left_height = Height(root->left);
    int right_height = Height(root->right);
    if (left_height > right_height)
    {
        return left_height + 1;
    }
    else
    {
        return right_height + 1;
    }
}

/*
             1
           /   \
          2     3
        /  \   /  \
       4    5 6    7
*/

int main()
{
    struct node *root = new node(1);
    root->left = new node(2);
    root->right = new node(3);
    root->left->left = new node(4);
    root->left->right = new node(5);
    root->right->left = new node(6);
    root->right->right = new node(7);
    cout << "Preorder Traversal: ";
    Preorder(root);
    cout << endl;
    cout << "Preorder Traversal: ";
    Postorder(root);
    cout << endl;
    cout << "Inorder Traversal: ";
    Inorder(root);
    cout << endl;
    cout << "The height of the tree is: ";
    cout << Height(root) << endl;
    return 0;
}

这是我得到的输出:

我在计算树的高度时遇到了这个错误。 我在函数高度中使用了 int 数据类型,即int Height(node *root),并且我正在返回值right_height + 1left_height + 1,但我仍然收到此错误。

【问题讨论】:

  • return; 不返回 int
  • @Eljay 但我正在返回值。主要问题在于 Height 函数。我返回值 right_height + 1 或 left_height + 1 但我仍然收到此错误。
  • Height 函数被声明为返回一个int 值。所以它必须返回一个int 值。还有一条执行路径,你 return 没有值。
  • Height 必须返回 int,但 return; 不返回任何内容。您必须修复 root == NULL 案例。
  • 在不相关的说明中,请不要使用旧的 C 兼容性宏 NULL,使用 nullptr

标签: c++ data-structures binary-tree


【解决方案1】:

当 root == NULL 时,您没有返回值。如果节点不存在,则树没有高度​​,因此应该返回 0。

int Height(node *root)
{
    if (root == NULL)
    {
        return 0;
    }

    int left_height = Height(root->left);
    int right_height = Height(root->right);
    if (left_height > right_height)
    {
        return left_height + 1;
    }
    else
    {
        return right_height + 1;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2011-10-02
    • 2011-10-26
    相关资源
    最近更新 更多