poj 1577 Falling Leaves

题目链接:
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值