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 = ; 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 < ) 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 - , postLeft, postLeft + index - midLeft - );
root->right = createTree(index + , midRight, postLeft + index - midLeft, postRight - );
return root;
} void preOrder(treeNode *root)
{
if (root != NULL)
{
cout << root->key << " ";
preOrder(root->left);
preOrder(root->right);
}
} int main()
{
/*************************
test.txt 文件内容如下:
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 = ; i < n; ++i)
cin >> midOrder[i]; for (int i = ; i < n; ++i)
cin >> postOrder[i]; treeNode *root = createTree(, n - , , n - );
cout << "The preOrder: " << endl;
preOrder(root);
cout << endl;
return ; }