題目鏈接:【HDU 1710】
輸入先序遍歷跟中序遍歷,輸出後序遍歷
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const int N=1010;
struct node
{
int v;
node *left , *right;
node():left(NULL),right(NULL){} //默認值
};
node* root;
void remove_tree(node* u)
{
if(u==NULL) return;
remove_tree(u->left);
remove_tree(u->right);
delete u;
}
node* newnode()
{
return new node;
}
node *create_tree(int* a, int* b , int n)
{
node* u=newnode();//創建一個新的節點
for(int i=0; i<n; i++)
{
if(a[0]==b[i]) //中序遍歷時的根節點
{
u->v = a[0];
u->left=create_tree(a+1, b, i);
u->right=create_tree(a+i+1, b+i+1, n-i-1);
return u;
}
}
return NULL;
}
void output(node* u)//輸出後序遍歷
{
if(u==NULL) return;
output(u->left);
output(u->right);
if(u==root) printf("%d\n", root->v);
else printf("%d ", u->v);
}
int main()
{
int n;
int a[N], b[N];
while(~scanf("%d", &n))
{
for(int i=0; i<n; i++) scanf("%d", &a[i]);
for(int i=0; i<n; i++) scanf("%d", &b[i]);
remove_tree(root);//清空樹
root = create_tree(a, b, n);
output(root);
}
return 0;
}
/*
9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6
*/