【NOIP2004】【Luogu1087】FBI树

本文介绍了一种使用C++实现的二叉树构建方法,通过对输入字符串的分析来构造二叉树,并实现了后序遍历输出。该方法首先检查每个节点的有效性,然后递归地构建左右子树。
problem
solution
codes
#include<stdio.h>
#define maxn 1<<12
using namespace std;
struct node{
    char t;
    int l, r;
    node():t('*'),l(0),r(0){}
}tree[maxn];
char s[maxn];
int top = -1;
char check(int le, int ri){
    int l=0, b=0;
    for(int i = le; i <= ri; i++){
        if(s[i]=='1')l=1;
        if(s[i]=='0')b=1;
    }
    if(l==1&&b==1)return 'F';
    if(l)return 'I';
    if(b)return 'B';
}
int build(int l, int r){
    if(l >= r){
        tree[++top].t = check(l,r);
        return top;
    }
    tree[++top].t = check(l,r);
    int now = top;
    int root = (l+r)/2;
    tree[now].l = build(l,root);
    tree[now].r = build(root+1,r);
    //printf("root:%d  top:%d\n",root,top+1);
    //printf("now:%d  lch:%d  rch:%d\n",now, tree[now].l,tree[now].r);
    return now;
}
void dfs(int root){
    //printf("root:%d %d %d\n",root,tree[root].l,tree[root].r);
    if(tree[root].l)dfs(tree[root].l);
    if(tree[root].r)dfs(tree[root].r);
    printf("%c",tree[root].t);
}
int main(){
    //freopen("data.in","r",stdin);
    int n;  scanf("%d%s",&n,s+1);
    n = 1<<n;
    build(1,n);
    dfs(0);
    return 0;
}

转载于:https://www.cnblogs.com/gwj1314/p/9444692.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值