【发布时间】: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 + 1 或left_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