生活随笔
收集整理的這篇文章主要介紹了
天勤数据结构高分笔记二叉排序树的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼為天勤數據結構高分筆記查找一章二叉排序樹
其下為具體的插入,刪除,查找,遍歷的實現與運行
#include<stdio.h>
#include<stdlib.h>
typedef struct BTNode
{int key
;struct BTNode
*lchild
,*rchild
;
}BTNode
;
BTNode
* BSTSearch(BTNode
*bt
,int key
){if(bt
==NULL)return NULL;else{if(bt
->key
==key
)return bt
;else if(bt
->key
>key
)return BSTSearch(bt
->lchild
,key
);else return BSTSearch(bt
->rchild
,key
); }
}
int Delete(BTNode
*&bt
){BTNode
*q
,*s
;if(!bt
->lchild
&&!bt
->rchild
)bt
=NULL;else if(!bt
->lchild
){q
=bt
;bt
=bt
->rchild
;free(q
);} else if(!bt
->rchild
){q
=bt
;bt
=bt
->lchild
;free(q
);} else{q
=bt
;s
=bt
->lchild
;while(s
->rchild
){q
=s
;s
=s
->rchild
;} bt
->key
=s
->key
;if(q
!=bt
)q
->rchild
=s
->lchild
;elseq
->lchild
=s
->lchild
;free(s
);}return 1;
}
int DeleteBST(BTNode
*&bt
,int key
){if(!bt
)return 0; else{if(key
==bt
->key
){Delete(bt
);return 1;}else if(bt
->key
>key
)return DeleteBST(bt
->lchild
,key
);elsereturn DeleteBST(bt
->rchild
,key
); }
}
int BSTInsert(BTNode
*&bt
,int key
){ if(bt
==NULL){bt
=(BTNode
*)malloc(sizeof(BTNode
));bt
->lchild
=bt
->rchild
=NULL;bt
->key
=key
;return 1; }else{if(bt
->key
==key
)return 0;else if(bt
->key
>key
)return BSTInsert(bt
->lchild
,key
);else return BSTInsert(bt
->rchild
,key
);}
}
void CreateBST(BTNode
*&bt
,int key
[],int n
){bt
=NULL;for(int i
=0;i
<n
;i
++)BSTInsert(bt
,key
[i
]);
}
void Order(BTNode
*bt
){if(bt
==NULL)return ;printf("%d ",bt
->key
);Order(bt
->lchild
);Order(bt
->rchild
);
} int main(){int key
[]={9,1,2,3,6,5,8};BTNode
*bt
,*temp
;CreateBST(bt
,key
,7);Order(bt
);temp
=BSTSearch(bt
,5); printf("\n%d\n",temp
->key
);DeleteBST(bt
,5);Order(bt
); return 0;
}
總結
以上是生活随笔為你收集整理的天勤数据结构高分笔记二叉排序树的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。