二叉搜索树(c实现)

来源:互联网 发布:软件实施投标文件 编辑:程序博客网 时间:2024/04/29 12:54

二叉检索树,并中序遍历

#include <stdio.h>#include <stdlib.h>typedef struct Node {int data;struct Node *left;struct Node *right;}Node ;void create_bst(Node **root,const int data){if(root==NULL){fprintf(stdout,"root is null");exit(-1);}if((*root)==NULL){*root = (Node*)malloc(sizeof(Node));(*root)->data = data;(*root)->left = NULL;(*root)->right = NULL;return ;} else {if((*root)->data > data){create_bst(&((*root)->left),data);} else {create_bst(&((*root)->right),data);}}}void print(Node *root){if(root==NULL){return ;} else {print(root->left);printf("%d ",root->data);print(root->right);}}int main(void){const int a[] = {9,8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8,9,0};const unsigned int  len = sizeof(a)/sizeof(int);Node* head = NULL;for(int i=0;i<len;i++){create_bst(&head,a[i]);}print(head);return 0;}


0 0
原创粉丝点击