构建原则: 左子树<根<右子树
//#--------------------------------
//#插入法生成二叉排序树//#--------------------------------
#include<stdio.h>
typedef struct BSTnode {
int data;
struct BSTnode *lchild, *rchild;
}*BSTnode;
void insert(BSTnode * root, int value) { //#插入函数,核心
if(! *root) {
(*root)=(BSTnode)malloc(sizeof(struct BSTnode)) ;
(*root)->data=value;
}
else {
if(value < (*root)->data) {
insert( &((*root)->lchild),value);
}
else {
insert( &((*root)->rchild),value);
}
}
}
BSTnode createBST(int arr[],int n) { // #生成BST
int tmp;
int i=0;
BSTnode root=NULL;
while (i < n) {
tmp=arr[i++];
insert(&root,tmp); //#传入&root的原因是:root的值会被改变
}
return root;
}
void MIDprint(BSTnode root) { // #中序遍历
if(root) {
MIDprint(root->lchild);
printf("%d\t",root->data);
MIDprint(root->rchild);
}
}
void PREprint(BSTnode root) { //#前序遍历
if(root) {
printf("%d\t",root->data);
PREprint(root->lchild);
PREprint(root->rchild);
}
}
int main() {
int arr[]={1,4,5,7,9,8,6};
BSTnode root=createBST(arr,7);
MIDprint(root); //#根据前序遍历和中序遍历可以知道生成的BST是什么样子
printf("\n");
PREprint(root);
printf("\n");
return 0;
}