uva 112 - Tree Summing题解

这个题如何输入是个难点,我一开始就觉得要用递归但是不知道怎么写,看了大牛的递归恍然大悟,在输入一个左括号之后再输入int a,如果输入的是右括号就输入错误,那个cin.good()的值就变为1,cin.clear()是用来清除输入错误,也就是把cin.good()置1。其实好多题目就是这样,想通了很简单,没想通觉得好复杂,如果有更加优化的算法,求各位师兄分享经验。

AC代码

#include<cstdio>
#include<ctype.h>
#include<algorithm>
#include<iostream>
#include<string.h>
using namespace std;
bool flag = false;
class node
{
public:
    node* lchlid;
    node* rchild;
};

node* treesum(int n,int sum)
{
    int a;
    char ch;
    node* root;
    cin>>ch;//左括号
    cin>>a;
    if(cin.good())
    {
        sum += a;
        root = new node;
        root->lchlid = treesum(n,sum);
        root->rchild = treesum(n,sum);
        if(!flag && root->lchlid == NULL && root->rchild == NULL)
            if(n == sum)
                flag = true;
        cin>>ch;//右括号
        return root;
    }
    else
    {
        cin.clear();//清楚错误状态
        cin>>ch;
        return NULL;
    }
}
int main()
{
//    freopen("input.txt","r",stdin);
    int n;
    while(cin>>n)
    {
        flag = false;
        treesum(n,0);
        if(flag)
            cout<<"yes"<<endl;
        else
            cout<<"no"<<endl;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值