欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

已知二叉树的中序遍历序列和后序遍历序列,求前序遍历序列

程序员文章站 2024-01-16 23:22:16
...

已知二叉树的中序遍历序列和后序遍历序列,求前序遍历序列

#include <bits/stdc++.h>
using namespace std;

char* in = (char *)malloc(sizeof(char));
char* post = (char *)malloc(sizeof(char));

struct node
{
    char data;
    node *left, *right;
};

node *create(int postL, int postR, int inL, int inR)
{
    if (postL > postR)
        return NULL;
    node *root = new node;
    root->data = post[postR];
    int k;
    for (k = inL; k < inR; k++)
        if (in[k] == post[postR])
            break;
    int num = k - inL;
    root->left = create(postL, postL + num - 1, inL, k - 1);
    root->right = create(postL + num, postR - 1, k + 1, inR);
    return root;
}

void preOrder(node *root)
{
    if (root == NULL)
        return;
    cout << root->data;
    preOrder(root->left);
    preOrder(root->right);
}

int main()
{
    scanf("%s", in);
    scanf("%s", post);
    int len = strlen(in);
    node *root = create(0, len - 1, 0, len - 1);
    preOrder(root);
    return 0;
}