数据结构之---C语言实现二叉排序树(BinarySortTree)
来源:互联网 发布:淘宝宝商城 编辑:程序博客网 时间:2024/05/22 02:03
这里又叫做二叉搜索树
代码:
//二叉排序树(二叉搜索树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;}
结果:
0 0
- 数据结构之---C语言实现二叉排序树(BinarySortTree)
- 二叉排序树(BinarySortTree)的实现
- 二叉排序树 C语言实现
- C语言实现二叉排序树
- 数据结构之(二叉排序树)
- 数据结构之栈(C语言实现)
- 数据结构之单链表(C语言实现)
- 数据结构之 队列(C语言实现)
- 数据结构之 栈(C语言实现)
- 数据结构之数组(C语言实现)
- 二叉排序树BinarySortTree(二叉搜索树Binary Search Tree)
- 创建二叉排序树C语言实现
- 二叉排序树C语言实现一
- 二叉排序树C语言实现二
- c语言:二叉排序树的实现
- C语言二叉排序树的实现
- 【数据结构与算法】二叉排序树C实现(含完整源码)
- 【数据结构与算法】二叉排序树C实现(含完整源码)
- 多图片批量上传
- 企业级Linux文件共享FTP入门和进阶(笔记)
- R语言读书笔记-02
- 使用C#,Matlab(2015a)混合编程
- 研一:开挂!过的很彪悍!
- 数据结构之---C语言实现二叉排序树(BinarySortTree)
- C实现二叉树的先序遍历,中序遍历,后序遍历
- 欢迎使用CSDN-markdown编辑器
- 黑马程序员——GUI——GUI概述与使用
- 安卓音乐播放器
- How to Keep Different Versions of gcc ?
- 引脚复用、CAN FIFO设置
- [HDU 2571 命运]简单DP
- 关于521