poj1145(二叉树

本文通过详细代码展示了如何解决POJ1145问题,虽然方法较为复杂,但作为二叉树操作的实践案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码长,,,其实解题不用这么麻烦的。。就当练习二叉树了QAQ。


#include <iostream>
#include <string>
using namespace std;
struct tree
{
    int data;
    tree *left,*right;
};
void clr(string a)
{
    for(string::iterator it = a.begin();it != a.end();++it)
        if ( *it != '(' && *it != ')' && (*it < 48 || *it > 57) && *it != '-')
            a.erase(it);
}
bool match(string a)
{
    int c = 0,b = 0;
    for(string::iterator it = a.begin();it != a.end();++it)
    {
        if(*it == '(')
            c++;
        if(*it == ')')
            b++;
    }
    if(c != b || a.size() == 0)
        return true;
    else return false;
}
void del(tree* &go)
{
    if(go != NULL)
    {
        if(go->left != NULL)
        del(go->left);
        if(go->right != NULL)
        del(go->right);
        delete go;
    }
    go = NULL;
}
unsigned int m = 0;
string trees = "";
void ft(tree* go,int all,int num,int& flag)
{
    if(m+1 < trees.size() && trees[m] == '(' && trees[m+1] != ')')
    {
        tree* make = new tree;
        go->left = make;
        int u = m+1,sum = 0,dis = 0;
        if(trees[m+1] == '-') {dis = 1;m ++;u++;}
        while(trees[u] > 47 && trees[u] < 58)
        {
            sum *= 10;
            sum += trees[u] - 48;
            u++;
            m = u - 2;
        }
        if(dis == 1) sum = -sum;
        make->data = sum;
        sum += all;
        m += 2;
        ft(go->left,sum,num,flag);
    }else
    {
        go->left = NULL;
        m += 2;
    }
    if(m+1 < trees.size() && trees[m] == '(' && trees[m+1] != ')')
    {
        tree* make = new tree;
        go->right = make;
        int u = m+1,sum = 0,dis = 0;
        if(trees[m+1] == '-') {dis = 1;m ++;u++;}
        while(trees[u] > 47 && trees[u] < 58)
        {
            sum *= 10;
            sum += trees[u] - 48;
            u++;
            m = u - 2;
        }
        if(dis == 1) sum = -sum;
        make->data = sum;
        sum += all;
        m += 2;
        ft(go->right,sum,num,flag);
    }else
    {
        go->right = NULL;
        m += 2;
    }
    m += 1;
    if(go->left == NULL && go->right == NULL && all == num)
        flag = 1;
}
int main()
{
    int num;
    while(cin >> num)
    {
        string mu;
        trees = "";
        m = 0;
        int flag = 0;
        tree forest,*go = &forest;
        go->left = go->right = NULL;
        while(match(trees))
        {
            cin >> mu;
            trees += mu;
        }
        clr(trees);
        ft(go,0,num,flag);
        del(go->left);
        if(flag == 1)
            cout << "yes" << endl;
        else cout << "no" << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值