题目链接:
poj 1577 Falling Leaves
题意:
给一个从下到上,从左到右的二叉搜索树的序列,让你根据这个序列建立相应的二叉搜索树,并按照前序遍历输出
思路:
将给的序列逆序建树,然后在前序遍历即可
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 1000005;
struct Node
{
char data;
Node *l, *r;
}node;
Node *Build(Node *rt,char val)
{
if(rt == NULL){
rt = new Node;
rt->data = val;
rt->l = rt->r = NULL;
return rt;
}
if(rt->data > val){
rt->l = Build(rt->l,val);
}
else{
rt->r = Build(rt->r,val);
}
return rt;
}
void for_order(Node *rt)
{
if(rt == NULL){
return ;
}
cout<<rt->data;
for_order(rt->l);
for_order(rt->r);
}
void free_tree(Node *rt)
{
if(rt == NULL){
return ;
}
free_tree(rt->l);
free_tree(rt->r);
delete rt;
}
int main()
{
char a,arr[505];
Node *rt = NULL;
memset(arr,0,sizeof(arr));
int cnt = 0;
while(cin>>a){
if(a >= 'A'&&a <= 'Z'){
arr[cnt++] = a;
}
else{
if(a == '*'||a == '$'){
for(int i = cnt - 1; i >= 0; i--){
rt = Build(rt,arr[i]);
}
for_order(rt);
cout<<endl;
cnt = 0;
memset(arr,0,sizeof(arr));
rt = NULL;
}
if(a == '$'){
free_tree(rt);
break;
}
}
}
return 0;
}