后序/中序--->前序

Posted on 2016-03-29 10:05  徐岩  阅读(140)  评论(0)    收藏  举报

preOrder 5 3 2 4 8 6 9   midOrder 2 3 4 5 6 8 9  postOrder 2 4 3 6 9 8 5

#include <iostream>
#include <cstdio>
using namespace std;

const int maxn = 100;

typedef struct Node
{
    int key;
    struct Node *left;
    struct Node *right;
}treeNode;

int midOrder[maxn];
int postOrder[maxn];

// 由后序和中序,得到前序
treeNode *createTree(int midLeft, int midRight, int postLeft, int postRight)
{
    if (postRight - postLeft < 0) return NULL;
    treeNode *root = new treeNode;
    root->key = postOrder[postRight];
    if (postLeft == postRight)
    {
        root->left = NULL;
        root->right = NULL;
    }
    int index;
    for (index = midLeft; index <= midRight; ++index)
    {
        if (midOrder[index] == postOrder[postRight]) break;
    }
    root->left = createTree(midLeft, index - 1, postLeft, postLeft + index - midLeft - 1);
    root->right = createTree(index + 1, midRight, postLeft + index - midLeft, postRight - 1);
    return root;
}

void preOrder(treeNode *root)
{
    if (root != NULL)
    {
        cout << root->key << " ";
        preOrder(root->left);
        preOrder(root->right);
    }
}

int main()
{
    /*************************
      test.txt 文件内容如下:
        7
        2 3 4 5 6 8 9
        2 4 3 6 9 8 5
    **************************/
    freopen("test.txt", "r", stdin);
int n;
    cin >> n;

    for (int i = 0; i < n; ++i)
        cin >> midOrder[i];

    for (int i = 0; i < n; ++i)
        cin >> postOrder[i];

    treeNode *root = createTree(0, n - 1, 0, n - 1);
    cout << "The preOrder: " << endl;
    preOrder(root);
    cout << endl;
    return 0;

}