112 - Tree Summing

 1 #include<iostream>
 2 using namespace std;
 3 int sum;
 4 int ok;
 5 struct node{
 6     int value;
 7     node* lchild;
 8     node* rchild;
 9 };
10 node* creat()
11 {
12     char ch;
13     cin>>ch;
14     int value;
15     if(cin>>value)
16     {
17         node* p=new node;
18         p->value=value;
19         p->lchild=creat();
20         p->rchild=creat();
21         cin>>ch;
22         return p;
23     }
24     else
25     {
26         cin.clear();
27         cin>>ch;
28         return NULL;
29     }
30 }
31 void allway(int n,node* p)
32 {
33     n=n+p->value;
34     if(p->lchild)
35         allway(n,p->lchild);
36     if(p->rchild)
37         allway(n,p->rchild);
38     if(sum==n&&!(p->lchild)&&!(p->rchild))
39         ok=1;
40 }
41 int main()
42 {
43     while(cin>>sum)
44     {
45         ok=0;
46         node* root=creat();
47         if(!root)
48         {
49             cout<<"no"<<endl;
50             continue;
51         }
52         allway(0,root);
53         cout<<(ok?"yes":"no");
54         cout<<endl;
55     }
56     return 0;
57 }

 

 

posted @ 2013-03-31 00:04  sooflow  阅读(122)  评论(0)    收藏  举报