问题描述
我已经用 C++ 编写了二叉树遍历及其高度,但是在经过一些编码后编译时,我不断收到错误:没有值的返回语句,在函数中返回“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
但我仍然收到此错误。
解决方法
当 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;
}
}