資料結構之---C語言實現二叉排序樹(BinarySortTree),---cbinarysorttree

來源:互聯網
上載者:User

資料結構之---C語言實現二叉排序樹(BinarySortTree),---cbinarysorttree

這裡又叫做二叉搜尋樹

代碼:

//二叉排序樹(二叉搜尋樹Binary Search Tree)//楊鑫#include <stdio.h>#include <stdlib.h>typedef struct node{int key;struct node *lchild, *rchild;}BSTNode, *BSTree;//插入int InsertBST(BSTree *bst, int k){BSTree r, s, pre;r = (BSTree)malloc(sizeof(BSTNode));r->key = k;r->lchild = NULL;r->rchild = NULL;if(*bst == NULL){*bst = r;return 1;}pre = NULL;s = *bst;while(s){if(k == s->key)return 0;else if(k < s->key){pre = s;s = s->lchild;}else{pre = s;s = s->rchild;}}if(k < pre->key)pre->lchild = r;elsepre->rchild = r;return 1;}void CreateBST(BSTree *bst){int key;*bst = NULL;scanf("%d", &key);while(key != -1){InsertBST(bst, key);scanf("%d", &key);}}/* *列印二叉樹: *中序遍曆 * */void InOrder(BSTree root){if(root != NULL){InOrder(root->lchild);printf(" %d ", root->key);InOrder(root->rchild);}}/* *搜尋 * */BSTree SearchBST(BSTree bst, int key){BSTree q;q = bst;//遞迴while(q){if(q->key == key)return q;if(q->key > key)q=q->lchild;elseq=q->rchild;}return NULL;                        //尋找失敗}int main(){BSTree T;int tag = 1;int m, n;printf("建立二叉排序樹,請輸入序列以-1結束:\n");CreateBST(&T);printf("中序遍曆二叉樹,序列為:\n");InOrder(T);printf("\n");while(tag != 0){printf("請輸入你要尋找的元素:\n");scanf("%d", &n);if(SearchBST(T, n) == NULL)printf("抱歉尋找失敗!\n");elseprintf("尋找成功!尋找的數字為%d\n", SearchBST(T,n)->key);printf("是否繼續尋找 是 :請按 1 否則按 0:\n");scanf("%d", &tag);}return 0;}


結果:


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.