c - 为什么我没有得到最后的打印语句,无法获得树的高度?
问题描述
在为节点取值后,程序终止。我不知道我做错了什么。我什至不知道这些值是否被插入。
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* GetNode(int data){
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->data=data;
newnode->left = NULL;
newnode->right = NULL;
}
struct Node* insert(struct Node* root,int data){
if(root=NULL){
root = GetNode(data);
return root;
}
else if(data <= root->data){
root->left = insert(root->left,data);
}
else{
root->right = insert(root->right,data);
}
return root;
}
int height(struct Node* root){
if(root==NULL){
return 0;
}
else{
int lh = height(root->left);
int rh = height(root->right);
if(lh>rh){
return (lh+1);
}
else{
return (rh+1);
}
}
}
int main() {
struct Node* root =NULL;
int n,i;
printf("Enter the total number of nodes in the tree: ");
scanf("%d",&n);
int value[n];
for(i=0;i<n;i++){
printf("Enter the %d node ",i+1);
scanf("%d",&value[i]);
}
for(i=0;i<n;i++){
root = insert(root,value[i]);
}
int high = height(root);
printf("Height of the given tree is : %d ",high);
return 0;
}
不,知道是高度函数还是插入函数。
解决方案
您的代码中有两个问题。
- 在函数
struct Node* GetNode(int data)
中,您没有返回newnode
. - 在函数
struct Node* insert(struct Node* root,int data)
中,在 if 条件if(root=NULL)
中,您应该使用==
这是更正后的工作代码:
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* GetNode(int data){
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->data=data;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
struct Node* insert(struct Node* root,int data){
if(root==NULL){
root = GetNode(data);
return root;
}
else if(data <= root->data){
root->left = insert(root->left,data);
}
else{
root->right = insert(root->right,data);
}
return root;
}
int height(struct Node* root){
if(root==NULL){
return 0;
}
else{
int lh = height(root->left);
int rh = height(root->right);
if(lh>rh){
return (lh+1);
}
else{
return (rh+1);
}
}
}
int main() {
struct Node* root =NULL;
int n,i;
printf("Enter the total number of nodes in the tree: ");
scanf("%d",&n);
int value[n];
for(i=0;i<n;i++){
printf("Enter the %d node ",i+1);
scanf("%d",&value[i]);
}
for(i=0;i<n;i++){
root = insert(root, value[i]);
}
int high = height(root);
printf("Height of the given tree is : %d ",high);
return 0;
}
推荐阅读
- python - 你如何将一个变量从一个 for 循环中取消本地化,并使其成为整个函数的本地变量?
- python - 如何在 pytorch 上的自定义数据集上训练 deeplabv3?
- swift - 返回类型不是可选的,但要求打开它
- r - 如何将 tidyGeocoder 与自定义地理编码器一起使用?
- python - 替换 Pandas 移位函数
- list - 如何将列表中的所有数据作为结构返回
- python - pyspark 列值是一个列表
- javascript - expo-video-player 在这个简单的库中使用 videoRef
- graphql - 带有打字稿的graphql - @FieldResolver 在compiled-to-js type-graphql 中不起作用
- spring - Kotlin 和 Spring MVC - HTTP 状态 400 - Null