二叉树 前序+中序>>后序

#include<stdio.h>
#include<string>
//using namespace std;

struct Node{
    Node *lch;
    Node *rch;
    char c;
}tree[50];

int n;//静态内存中已经分配的节点个数
Node *create(){//申请节点空间并返回其指针
    tree[n].lch = tree[n].rch = NULL;
    return &tree[n++];
}

char str1[27], str2[27];
//后序遍历
void postOrder(Node* t){
    if (t->lch != NULL)
    {
        postOrder(t->lch);
    }
    if (t->rch != NULL)
    {
        postOrder(t->rch);
    }
    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] == ret->c)
        {
            rootidx = i;
            break;
        }
    }
    //左子树不为空
    if (rootidx != s2)
    {
        ret->lch = build(s1 + 1, s1 + rootidx - s2, s2, rootidx - 1);
    }
    if (rootidx != e2)
    {
        ret->rch = build(s1 + rootidx - s2 + 1, e1, rootidx + 1, e2);
    }
    return ret;
}

void main()
{
    while (scanf("%s", str1)!=EOF)
    {
        scanf("%s", str2);
        int len1 = strlen(str1);
        int len2 = strlen(str2);
        n = 0;
        Node*root = build(0, len1-1, 0, len2-1);
        postOrder(root);
        printf("\n");
    }
    


}

猜你喜欢

转载自blog.csdn.net/KingsCC/article/details/81708603