二叉树遍历

来源:互联网 发布:重庆seo网站推广 编辑:程序博客网 时间:2024/06/07 15:39
/*已知前序和中序,得到后序**/#include <stdio.h>#include <string.h>struct Node {    Node *lchild ;    //左儿子指针     Node *rchild ;    //右儿子指针     char c;    //结点字符信息 }Tree[50];    //静态内存分配数组 int loc;    //静态数组中已经分配的节点个数 Node* create() {    Tree[loc].lchild = Tree[loc].rchild = NULL;    return &Tree[loc ++];}char str1[30], str2[30];void postOrder(Node *T ) {    //后序遍历     if(T -> lchild != NULL) {    //左子树不空           postOrder(T -> lchild );  }      if(T -> rchild != NULL) {         postOrder(T -> rchild );  }    printf("%c",T -> c);}Node *build (int s1, int e1, int s2, int e2) {    Node *ret = create();   //为该树根节点申请空间    ret ->c = str1[s1];     //该节点字符为前序遍历中第一个字符     int rootIdx;    for(int i =s2; i <=e2; i++) {        if(str2[i] == str1[s1]) {              rootIdx = i;     //找到根节点在中序遍历中的位置             break;        }    }    if(rootIdx != s2) {     //若左子树不为空         ret -> lchild = build(s1 +1, s1 +(rootIdx -s2), s2, rootIdx-1);     }    if(rootIdx != e2) {    //若右子树不为空         ret ->rchild = build(s1+(rootIdx-s2) +1, e1, rootIdx+1, e2);    }    return ret;}int main() {    while(scanf("%s",str1) != EOF ) {    //输入前序遍历         scanf("%s",str2);                //输入中序遍历         loc = 0;                        //初始化静态内存空间中已经使用节点个数为0         int L1 = strlen(str1);                 int L2 = strlen(str2);         //计算两个字符串长度         Node *T = build (0, L1-1, 0, L2-1);   //还原整棵树,其根节点指针保存在 T 中         postOrder(T );    //后序遍历         printf("\n");    }    return 0;}

/*输出结果:

ABC
BAC
BCA

FDXEAG
XDEFAG
XEDGAF
*/