线索二叉树

来源:互联网 发布:僵尸相机软件 编辑:程序博客网 时间:2024/06/05 12:03
#include <stdio.h>#include <stdlib.h>typedef struct node{    char data;    struct node * lchild;    struct node * rchild;    int ltag;    int rtag;}TBTree;TBTree * pre;//创建一颗二叉树TBTree * create(TBTree * t){    char ch;    scanf("%c",&ch);    if(ch != ' '){        t = (TBTree *)malloc(sizeof(TBTree));        t->data = ch;        t->lchild = create(t->lchild);        t->rchild = create(t->rchild);        return t;    }else{        return NULL;    }   }void thread(TBTree * t){    if(t != NULL){        thread(t->lchild);        if(t->lchild == NULL){            t->lchild = pre;            t->ltag = 1;        }else{            t->ltag = 0;        }        if(pre->rchild == NULL){            pre->rchild = t;            pre->rtag = 1;        }else{            pre->rtag = 0;        }        pre = t;        thread(t->rchild);    }   }//建立中序线索二叉树TBTree * createThread(){    TBTree * t,* p;    t = create(p);    TBTree * root;    root = (TBTree *)malloc(sizeof(TBTree));    root->ltag = 0;    root->rtag = 1;    if(t == NULL){        root->lchild = root;    }else{        root->lchild = t;        pre = root;        thread(t);        root->rchild = pre;        pre->rchild = root;         pre->rtag = 1;    }       return root;}//中序遍历线索二叉树void inorderPrint(TBTree * root){    TBTree * t;    t = root->lchild;    while(t != root){        while(t->ltag == 0){            t = t->lchild;        }        printf("%3c",t->data);        while(t->rtag == 1 && t->rchild != root){            t = t->rchild;            printf("%3c",t->data);        }        t = t->rchild;    }   }int main(){    TBTree * root;    root = createThread();    inorderPrint(root);    printf("\n");    return 0;}
0 0