首页 > 解决方案 > 为什么我没有得到最后的打印语句,无法获得树的高度?

问题描述

在为节点取值后,程序终止。我不知道我做错了什么。我什至不知道这些值是否被插入。

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;
}

不,知道是高度函数还是插入函数。

标签: cbinary-treebinary-search-tree

解决方案


您的代码中有两个问题。

  1. 在函数struct Node* GetNode(int data)中,您没有返回newnode.
  2. 在函数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;
}

推荐阅读