为什么我没有得到最后的打印语句,无法获得树的高度?

Why am I not getting the last print statement, unable to get height of the tree?

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

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

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

您的代码有 2 个问题。

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