BST.H #ifndef _BST_H #define _BST_H #define NONE -1 typedef enum{FALSE, TRUE}Status; typedef int ElemType; typedef struct _tNode { ElemType data; struct _tNode *lChild; struct _tNode *rChild; }TreeNode, BST; BST *initBST(); Status searchBST(BST *t, ElemType e); Status insertBST(BST *t, ElemType e); #endif BST.CPP main函数里首先建立树根,然后进行搜索,没有搜到到的数执行插入 #include "BST.h" #include <stdlib.h> //************************************ // Method: initBST // FullName: initBST // Access: public // Returns: BST * // Qualifier: // Parameter: ElemType e //************************************ BST *initBST(ElemType e) { BST *t; t = (BST *)malloc(sizeof(BST)); if(t == NULL) return NULL; t->data = e; t->lChild = NULL; t->rChild = NULL; return t; } //************************************ // Method: searchBST // FullName: searchBST // Access: public // Returns: Status // Qualifier: // Parameter: BST * t // Parameter: ElemType e //************************************ Status searchBST(BST *t, ElemType e) { BST *p = NULL; if(t == NULL) return FALSE; p = t; if(e == p->data) return TRUE; if(searchBST(p->lChild, e)) return TRUE; if(searchBST(p->rChild, e)) return TRUE; return FALSE; } //************************************ // Method: insertBST // FullName: insertBST // Access: public // Returns: Status // Qualifier: // Parameter: BST * t // Parameter: ElemType e //************************************ Status insertBST(BST *t, ElemType e) { BST *p = NULL, *temp = NULL; if(t == NULL) return FALSE; p = t; temp = (BST *)malloc(sizeof(BST)); if(temp == NULL) return FALSE; temp->data = e; temp->lChild = NULL; temp->rChild = NULL; if(e < p->data && !(p->lChild)) { p->lChild = temp; return TRUE; } else if(e < p->data) return insertBST(p->lChild, e) == TRUE? TRUE:FALSE; if(e > p->data && !(p->rChild)) { p->rChild = temp; return TRUE; } else if(e > p->data) return insertBST(p->rChild, e) == TRUE? TRUE:FALSE; return FALSE; } //************************************ // Method: main // FullName: main // Access: public // Returns: int // Qualifier: //************************************ int main() { BST *t = initBST(45); if(!searchBST(t, 24)) insertBST(t, 24); if(!searchBST(t, 53)) insertBST(t, 53); if(!searchBST(t, 52)) insertBST(t, 52); if(!searchBST(t, 23)) insertBST(t, 23); if(!searchBST(t, 25)) insertBST(t, 25); if(!searchBST(t, 55)) insertBST(t, 55); if(!searchBST(t, 54)) insertBST(t, 54); return 0; }