Tan*_*pta 1 c++ binary-tree data-structures
我已经用 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;
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
我在计算树的高度时遇到此错误。我在函数 height 中使用了 int 数据类型,int Height(node *root)并且我也返回了值right_height + 1,left_height + 1但仍然收到此错误。
小智 5
当 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1296 次 |
| 最近记录: |