POJ 1145 (二叉树的遍历)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>

using namespace std;

struct tree
{
    int data;
    tree *left,*right;
};

int m=0;
string trees="";

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;
}

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(isdigit(trees[u])){
            sum*=10;
            sum+=trees[u]-48;
            u++;
            m++;
        }
        if(dis==1)
            sum=-sum;
        make->data=sum;
        sum+=all;
        m++;
        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(isdigit(trees[u])){
            sum*=10;
            sum+=trees[u]-48;
            u++;
            m++;
        }
        if(dis) sum=-sum;
        sum+=all;
        m++;
        ft(go->right,sum,num,flag);
    }else{
        go->right=NULL;
        m+=2;
    }
    m++;
    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 *go=new tree;
        go->left=go->right=NULL;
        char ch;
        int x=0;
        while(cin>>ch){
            if(ch!=' ')
                trees+=ch;
            if(ch=='(') x++;
            if(ch==')') x--;
            if(x==0) {
                break;
            }
        }
//        cout<<trees<<endl;
        ft(go,0,num,flag);
        del(go);
        if(flag)
            cout<<"yes"<<endl;
        else
            cout<<"no"<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值