1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include <stdio.h> #include <stdlib.h>
#define true 1 #define false 0
typedef int elementType;
typedef struct bst { elementType data; struct bst *left; struct bst *right; }BST,*PBST;
PBST create_bst(int root_data); int insert_node(PBST *bst,int data); void print_inorder(PBST tree);
void main() { int in; printf("请输入根节点的值"); scanf("%d",&in);
PBST bst = create_bst(in); insert_node(&bst,2); insert_node(&bst,3); insert_node(&bst,4); insert_node(&bst,5); insert_node(&bst,6);
print_inorder(bst); }
PBST create_bst(int root_data) { PBST bst = (PBST)malloc(sizeof(PBST)); if(bst == NULL) { printf("malloc apply fail"); exit(-1); }
bst->data = root_data; bst->left = NULL; bst->right = NULL;
return bst; }
void create_node(PBST child,int data) { child = (PBST)malloc(sizeof(PBST)); child->data = data; child->left = child->right = NULL; }
int insert_node(PBST *bst,int data) { if(!(*bst)) { PBST temp = (PBST)malloc(sizeof(PBST)); temp->left = temp->right = NULL; temp->data = data; *bst = temp; return ; }
if (data < (*bst)->data) { insert_node(&((*bst)->left),data); }else if (data > (*bst)->data) { insert_node(&((*bst)->right),data); } }
void print_inorder(PBST tree) { if(tree) { print_inorder(tree->left); printf("%d\n",tree->data); print_inorder(tree->right); } }
|