微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C语言中的结构,指针和二进制搜索树

如何解决C语言中的结构,指针和二进制搜索树

以下代码仅能向树添加一个元素。 请检查此代码有什么问题。 我尝试创建一个具有8个节点的二进制搜索树,并从数组中获取值,当我打印树时,仅打印第一个元素,即数组的第一个元素。 可能是我对结构和指针的工作不满意。您能否详细说明c语言中的指针和结构。 感谢您的帮助。

#include<stdio.h>
#include<stdlib.h>                                
struct node{                                              
        int data;
        struct node *left;
        struct node *right;                       
};

struct node *root=NULL;

void add(struct node**,struct node*);

void createtree(struct node **root){
        int arr[8]={20,45,17,56,40,32,25,48};
        int size=sizeof(arr)/sizeof(int);
        struct node *temp=NULL;
        for(int i=0;i<size;i++)
        {
                temp=(struct node *)malloc(sizeof(
struct node));
                temp->data=arr[i];
                temp->left=NULL;
                temp->right=NULL;
                add(root,temp);
        }
}
void add(struct node **root,struct node *temp){
        if(*root==NULL){
                *root=temp;
                return;
        }
        struct node *curr=*root;
        if(temp->data< curr->data){
                struct node *temper=curr->left;
                add(&temper,temp);
        }
        else
        {
                struct node *temper=curr->right;
                add(&temper,temp);
        }                                         
}
void print(struct node *root){
        if(root!=NULL){
                print(root->left);
                printf("%d ",root->data);
                print(root->right);
        }
}                                                                                                   
int main(){                                               
        createtree(&root);                                
        print(root);
        return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。