#include <iostream>
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct BSTNode{
int data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BiTree;
//二叉排序树的插入
int BST_Insert(BiTree &T,int key){
if(T==NULL){
T = (BSTNode*)malloc(sizeof(BSTNode));
T->data = key;
T->lchild = T->rchild = NULL;
return 1;
}
else if(key == T->data){
return 0;
}
else if(key > T->data){
return BST_Insert(T->rchild,key);
}
else{
return BST_Insert(T->lchild,key);
}
}
//二叉排序树的查找
BSTNode* BST_Search(BiTree T,int key){
if(T==NULL){
return NULL;
}
else if(key > T->data){
return BST_Search(T->rchild);
}
else{
return BST_Search(T->lchild);
}
}
//构造二叉排序树
void Create_BST(BiTree &T,int num[],int n){
T = NULL;
int i = 0;
while(i<n){
BST_Insert(T,num[i]);
i++;
}
}
int main(int argc, char** argv) {
int num[] = {1,2,3,4,5};
BiTree T;
Create_BST(T,num,5);
BST_Search(T,3);
return 0;
}
原文:https://blog.51cto.com/14049943/2612117