/* Binary threading tree can be used where frequent searching are needed. * Because there is no recursive function and the codes run quite efficiently. */ #include "/usr/c/head.h" typedef char elemtype; typedef enum {link, thread} pointertag; typedef struct bitreenode { elemtype data; struct bitreenode * lchild, * rchild; pointertag ltag, rtag; }bitreenode, * bitree; bitree pre; status creat_tree(bitree * T) { elemtype ch; int temp; printf("Input element:"); SCAN_CHAR(ch, temp); if (ch == ' ') *T = NULL; else { *T = (bitree)malloc(sizeof(bitreenode)); if (!(*T)) exit(OVERFLOW); (*T)->data = ch; creat_tree(&(*T)->lchild); creat_tree(&(*T)->rchild); if ((*T)->lchild) (*T)->ltag = link; else (*T)->ltag = thread; if ((*T)->rchild) (*T)->rtag = link; else (*T)->rtag = thread; } return OK; } status visit(bitree p) { printf("%c/tltag = %d. rtag = %d./n", p->data, p->ltag, p->rtag); return OK; } status in_order_traverse(bitree T) { if (T) { in_order_traverse(T->lchild); visit(T); in_order_traverse(T->rchild); } return OK; } status inthreading(bitree p) { if (p) { inthreading(p->lchild); if (!p->lchild) p->lchild = pre; if (!pre->rchild) pre->rchild = p; pre = p; inthreading(p->rchild); } return OK; } status in_order_threading(bitree * thrt, bitree T) { *thrt = (bitree)malloc(sizeof(bitreenode)); if (!(*thrt)) exit(OVERFLOW); (*thrt)->ltag = link; (*thrt)->rtag = thread; (*thrt)->rchild = *thrt; if (!T) (*thrt)->lchild = *thrt; else { (*thrt)->lchild = T; pre = *thrt; inthreading(T); pre->rtag = thread; pre->rchild = *thrt; (*thrt)->rchild = pre; } return OK; } status in_order_traverse_thrt(bitree thrt) { bitree p; p = thrt->lchild; while (p != thrt) { while (p->ltag == link) p = p->lchild; visit(p); while (p->rtag == thread && p->rchild != thrt) { /* Be carefull here, if "p->rchild != thrt" is missed, the function will step into endless loop.*/ p = p->rchild; visit(p); } p = p->rchild; } return OK; } int main(void) { bitree T; bitree thrt; creat_tree(&T); printf("In_order_traverse:/n"); in_order_traverse(T); in_order_threading(&thrt, T); printf("In_order_traverse_thrt:/n---------------------------/n");; in_order_traverse_thrt(thrt); return 0; }