112 – Tree Summing

來源:互聯網
上載者:User
交啦好幾次運行錯誤,原來是數組開小了,快哭死了,本體沒別的痛點,就是建一個簡單的二叉樹,然後用遞迴取值就行了,如果學的比較好的話可以不建樹就能做 #include <iostream>#include <cstdio>#include <cstring>#include <stack>using namespace std;int N,flag; struct p{    int pri;    p *left,*right;} ;p *root;void sum(p *y,int n){    if(y!=NULL)    {        if(y->left==NULL&&y->right==NULL)        {            n+=y->pri;            if(n==N)flag=1;        }        if(y->left!=NULL)            sum(y->left,n+y->pri);        if(y->right!=NULL)            sum(y->right,n+y->pri);    }}int main(){    //freopen("a.txt","r",stdin);    int i,count1,count2,count,j,k;    char s,str[10100];    while(scanf("%d",&N)!=EOF)    {        stack<p *> v;        memset(str,0,sizeof(str));        count1=count2=count=0;        while(1)        {            scanf("%c",&s);            if(s=='(')count1++;            else if(s==')')count2++;            if(s=='('||s==')'||s=='-'||(s>='0'&&s<='9'))                str[count++]=s;            if(count1==count2&&count1!=0)break;        }        getchar();        for(i=count-1; i>=0; i--)        {            if(str[i]==')'&&str[i-1]=='(')            {                root=new p;                root->left=root->right=NULL;                root->pri=0;                root=NULL;                v.push(root);                i--;            }            else if(str[i]>='0'&&str[i]<='9')            {                j=i;                count1=count2=0;                for(i=i-1;; i--)                    if(str[i]<'0'||str[i]>'9')break;                for(k=i+1; k<=j; k++)                    count1=count1*10+str[k]-'0';                if(str[i]=='-')count1=0-count1;                else ++i;//這裡要特別注意,一定要有,即便uva的測試資料不準確,但要考慮到                root=new p;                root->pri=count1;                p *root1,*root2;                root1=v.top();                v.pop();                root2=v.top();                v.pop();                root->left=root1;                root->right=root2;                v.push(root);            }        }        flag=0;        sum(v.top(),0);        if(flag)printf("yes\n");        else printf("no\n");    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.