二叉排序树
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode{
int data;
struct TreeNode* lchild;
struct TreeNode* rchild;
}TreeNode;
//二叉排序树的插入
void bstInsert(TreeNode** tree,int x){
if(*tree==NULL){
*tree=(TreeNode*)malloc(sizeof(TreeNode));
(*tree)->data=x;
(*tree)->lchild=NULL;
(*tree)->rchild=NULL;
}
/*相等的情况,二叉排序树应该没有相等元素
else if((*tree)->data==x)
return;
*/
else if((*tree)->data>x)
bstInsert(&((*tree)->lchild),x);
else
bstInsert(&((*tree)->rchild),x);
}
//测试插入是否正确
void preOrder(TreeNode* tree){
if(tree){
printf("%d ",tree->data);
preOrder(tree->lchild);
preOrder(tree->rchild);
}
}
int main(int argc, const char *argv[])
{
TreeNode* tree=NULL;
int n[5]={10,8,21,2,2},i;
for(i=0;i<5;i++)
bstInsert(&tree,n[i]);
preOrder(tree);
puts("");
return 0;
}