您的位置:首页 > 其它

HDU 1710 Binary Tree Traversals(已知先序中序求后序)

2016-03-05 15:14 381 查看
题目链接:【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
, b
;
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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: