排序二叉树

来源:互联网 发布:超级碧业生 知乎 编辑:程序博客网 时间:2024/06/18 04:45

排序二叉树的基本操作


#include "StdAfx.h"#include <stdio.h>#include <stdlib.h>#define MAXSIZE 5typedef int Elemtype;typedef struct BSTNode{    Elemtype data;    BSTNode *lchild,*rchild,*parent;}BSTNode,*BSTree;void InsertBST(BSTree *T,int key){    BSTree p=(BSTree)malloc(sizeof(BSTNode));    p->data = key;    p->lchild=p->rchild=p->parent = NULL;        if(*T == NULL)    {        *T=p;return;    }if((*T)->data == key)return;/*if( (*T)->data > key && (*T)->lchild ==NULL){p->parent = *T;(*T)->lchild = p;return;}if( (*T)->data <key && (*T)->rchild == NULL){p->parent = *T;(*T)->rchild = p;return;}*/if( (*T)->data > key ){InsertBST( &(*T)->lchild,key);}else if( (*T)->data < key){InsertBST( &(*T)->rchild,key);}else return;}void CreatBST(BSTree *T,Elemtype *a,int n){//printf("请输入创建二叉树的数据(int)的个数:");//scanf("%d",&n);    //printf("请输入创建二叉树的数据(int):\n");//for(int i=0;i<n;i++)//{//scanf("%d",&a[i]);//}for(int i=0;i<n;i++){InsertBST(T,a[i]);}}void Visit(BSTree T){if(T){Visit(T->lchild);printf("%d ",T->data);Visit(T->rchild);}}BSTree search(BSTree T,Elemtype key){if(!T){printf("查找失败!\n");return T;}if(key == T->data){printf("查找成功,查找的值所在子树为:");return T;}else if(key < T->data)return search(T->lchild,key);elsereturn search(T->rchild,key);}void Delete(BSTree *p){BSTree q=NULL;BSTree s=NULL;if( (*p)->lchild == NULL){q=*p;*p=(*p)->rchild;free(q);}else if( (*p)->rchild ==NULL){q=*p;*p=(*p)->lchild;free(q);}else{q=*p;s=(*p)->lchild;while(s->rchild){q=s;s=s->rchild;}(*p)->data=s->data;if(q != *p){//(*p)->data=s->data;q->rchild=s->lchild;}else{q->lchild=s->lchild;}}free(s);}void deleteBST(BSTree *T,int key){if(*T == NULL){printf("删除失败!");return;}if((*T)->data == key){Delete(T);}else if(key < (*T)->data){deleteBST(&(*T)->lchild,key);}else if(key > (*T)->data){deleteBST(&(*T)->rchild,key);}}int main(){int n;BSTree T =NULL;BSTree temp=NULL;Elemtype a[7]={45,12,36,78,5,41,63};//printf("请输入创建二叉排序树的数据(int)的个数:");//scanf("%d",&n);//Elemtype a[n];CreatBST(&T,a,7);Visit(T);printf("\n");temp=search(T,1);Visit(temp);InsertBST(&T,13);Visit(T);printf("\n");deleteBST(&T,45);Visit(T);return 0;}


0 0