2016夏季练习——二叉树

本文介绍了一种通过特定输入方式构建二叉搜索树的方法,并详细展示了如何使用递归算法进行节点插入及前序遍历输出。

来源:POJ1577

建树还是很简单的,但是这个题目的输入很值得玩味,可以说没有这样的输入,代码如此顺利是不可能的

代码:

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXN = 40;
char mp[MAXN][MAXN];
int cnt;
struct Tree{
    int l,r;
    char ch;
    Tree():l(0),r(0){}
    void ini(){
        l=r=0;
    }
};
Tree tree[MAXN];
int ptr;
void push(int rt,char data){
    if(data<tree[rt].ch){
        if(tree[rt].l==0){
            tree[rt].l=ptr;
            tree[ptr].ch=data;
            tree[ptr].ini();
        }
        else push(tree[rt].l,data);
    }
    else{
        if(tree[rt].r==0){
            tree[rt].r=ptr;
            tree[ptr].ch=data;
            tree[ptr].ini();
        }
        else push(tree[rt].r,data);
    }
}
void preorder(int rt){
    printf("%c",tree[rt].ch);
    if(tree[rt].l) preorder(tree[rt].l);
    if(tree[rt].r) preorder(tree[rt].r);
}
int main(){
    cnt=0;
    while(scanf("%s",mp[cnt++])!=EOF){
        if(mp[cnt-1][0]=='*'||mp[cnt-1][0]=='$'){
            ptr=0;
            for(int i=0;i<MAXN;++i) tree[i].ini();
            tree[ptr].ch=mp[cnt-2][0];
            for(int i=cnt-3;i>=0;i--){
                int len = strlen(mp[i]);
                for(int j=0;j<len;j++){
                    ptr++;
                    push(0,mp[i][j]);
                }
            }
            preorder(0);
            cout<<endl;
            if(mp[cnt-1][0]=='$') break;
            cnt=0;
        }
    }
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值