一直不敢写树的题,这道一次过,其实写的时候仔细点就行,和人工的思路一样
#include <iostream>
#include <queue>
#include <stdio.h>
using namespace std;
int n;
int *postorder;
int *inorder;
struct Info
{
int value;
Info *left;
Info *right;
};
int findIn(int element, int start, int end)
{
for(int i = start; i <= end; i++)
{
if(inorder[i] == element)
return i-start;
}
return -1;
}
void build(Info *tree, int poststart, int postend, int instart, int inend)
{
int root = postorder[postend];
tree->value = root;
if(instart == inend)
{
tree->left = NULL;
tree->right = NULL;
return;
}
int site = findIn(root, instart, inend);
if(site == 0)
tree->left = NULL;
else
{
tree->left = new Info;
build(tree->left, poststart, poststart + site - 1, instart, instart + site-1);
}
if(site == inend-instart)
tree->right = NULL;
else
{
tree->right = new Info;
build(tree->right, poststart + site, postend-1, instart + site + 1, inend);
}
}
void leveloutput(Info *tree)
{
bool first = true;
Info *info;
queue<Info*> output;
output.push(tree);
while(!output.empty())
{
info = output.front();
output.pop();
if(first)
cout << info->value;
else
cout << " " << info->value;
first = false;
if(info->left != NULL)
output.push(info->left);
if(info->right != NULL)
output.push(info->right);
}
}
int main()
{
cin >> n;
postorder = new int[n];
inorder = new int[n];
for(int i = 0; i < n; i++)
cin >> postorder[i];
for(int i = 0; i < n; i++)
cin >> inorder[i];
Info tree;
build(&tree,0, n-1, 0, n-1);
leveloutput(&tree);
return 0;
}