查找(二)动态查找:二叉排序树的插入与输出操作
2013-08-03 17:22
363 查看
#include<stdio.h> #include<stdlib.h> #include<stack> using namespace std; #define N 10 #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define EQ(a,b) ((a)==(b)) #define LT(a,b) ((a)<(b)) #define LQ(a,b) ((a)<=(b)) typedef int KeyType; struct ElemType { KeyType key; int others; }; typedef ElemType TElemType; typedef struct BiTNode { TElemType data; BiTNode *lchild,*rchild; }BiTNode,*BiTree; int InitDSTable(BiTree &DT) { //操作结果:构造一个空的动态查找表DT DT = NULL; return OK; } int SearchBST(BiTree T,KeyType key,BiTree f,BiTree &p) { //在根指针T所指二叉排序树中非递归地查找某个关键字等于key的数据元素,查找成功 //则p指向该数据元素结点,并返回TRUE;否则指针p指向查找路径上访问的最后一个结点, //并返回FALSE. BiTree q; if(!T) { p = f;return FALSE; } q = T; //查找过程每次都是从根结点出发,当q指向的地址为空时,p刚好指向q上一次指向的地址,因此在 InsertBST 函数中对p的左孩子右孩子赋值,正好就是应该插入的位置 while(q) { if ( EQ(key,q->data.key) ) { p = q; return TRUE; } else if LT(key,q->data.key) { p = q;q = q->lchild;} else { p = q;q = q->rchild;} } return FALSE; } int InsertBST(BiTree &T, ElemType e) { //当二叉排 序树T中不存在关键字等于e.key的数据元素时,插入e并返回TRUE,否则返回FALSE BiTree p,s; if( !SearchBST(T,e.key,NULL,p) )//查找不成功 { s =(BiTree)malloc(sizeof(BiTNode)); s->data = e; s->lchild = s->rchild = NULL; if(!p) T = s; //被插结点 *s为新的根结点 else if LT(e.key,p->data.key) p->lchild =s;//被插结点 *s为左孩子 else p->rchild = s; //被插结点 *s为右孩子 return TRUE; } else return FALSE;//树中已有关键字相同的结点,不再插入 } void print(ElemType c) { printf("(%d,%d)\n",c.key,c.others); } int visit(ElemType c) { printf("%d",c); return OK; } void TraverseDSTable(BiTree T) { //递归中序遍历,可以得到从小到大的有序序列 if ( T ) { TraverseDSTable(T->lchild); //printf(" %d",T->data.key); print(T->data); TraverseDSTable(T->rchild); } } void TraverseDSTable1(BiTree T) { //非递归中序遍历 BiTree p = T; stack<BiTree> s ; while ( p || !s.empty() ) { if ( p ) { s.push(p); p = p->lchild; } else { //Pop(S,p); p = s.top(); s.pop(); print(p->data); //第二次经过该结点时打印出来 p = p->rchild; } } } int main() { BiTree dt,p; int i; KeyType j; ElemType r = { {45,1},{12,2},{53,3},{3,4},{37,5},{24,6},{100,7},{61,8},{90,9},{78,10}}; InitDSTable(dt);//构造空表 for(i=0;i<N;i++) InsertBST(dt,r[i]);//依次插入数据元素 TraverseDSTable1(dt); system("pause"); return 0; }
相关文章推荐
- 二叉排序树的操作(建立、插入、删除和查找)
- 二叉排序树的查找和插入操作 - 数据结构和算法74
- 二叉排序树的相关操作(插入,查找,删除,遍历等)
- 二叉排序树的基本操作(建立,中序遍历,查找,删除,插入)
- 链表的基本操作(C语言版):建立,插入,删除,查找,输出
- 单链表的创建、初始化、插入、删除 、输出、求表长、清空、查找操作
- 编程菜鸟的日记-初学尝试编程-顺序表的类定义及其基本操作算法(创建表、元素插入、元素删除、顺序查找、测表空、求表长、输出等)
- c语言:顺序表的实现(一) 创建,插入,删除,查找,输出等基本操作实现
- C++实现顺序表的常用操作(插入删出查找输出)
- 顺序表的实现以及简单的 插入,删除,查找,输出操作
- 二叉排序树的插入、生成、删除及查找操作
- 数据结构与算法分析--二叉排序树(二叉查找树,二叉搜索树)的查找、插入和删除操作
- C语言实现双向链表删除节点、插入节点、双向输出等操作
- 二叉排序树(插入、删除、查找)
- 二分法的应用----------利用随机类生成数组,并用二分法对数组的元素进行查找以及插入操作
- 二叉排序树的查找、插入和删除
- 创建、删除、插入、输出输出动态链…
- C++ 单链表操作 插入、删除、查找、排序、合并
- 二叉排序树的创建,插入和 删除操作
- 动态生成多条插入语句如:insert into MyStudents values(“人名1”,年龄,‘男’,分数1,分数2)。将生成的插入语句输出到记事本文件 SQLStr.txt中