#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[N] = { {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; }