二叉排序樹是一種便於查找的一種有序樹。其中二叉排序樹的左子樹均小於其根結點的值,右子樹均大於其根結點的值。因此二叉排序樹是一種遞歸的方式創建和查詢以及插入。因爲二叉樹的刪除有點兒複雜,因此沒有給出代碼。刪除大致上是三種狀況:1.直接刪除葉子結點2.刪除只帶有一個分支的結點,讓其分支節點直接代替其根結點3.刪除多個分支的結點,讓刪除結點的中序序列直接後繼代替被刪結點。下面請看詳細的代碼:ios
#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; }