建树并遍历即可(可以不用建树)难点在于建树。
#include<stdio.h>
#include<cstring>
struct tree
{
int date;
tree *l,*r;
tree()
{
date=0;
l=r=NULL;
}
};
tree* built()
{
tree *now=new tree;
now->date=0;
now->l=now->r=NULL;
int cnt=0,flag=0;
char ch;
while((ch=getchar())!=EOF)
{
if(ch>='0'&&ch<='9')now->date=now->date*10+ch-'0';
else if(ch=='(')
{
if(!cnt)now->l=built();
else if(cnt==1)now->r=built();
cnt++;
}
else if(ch=='-')flag=1;
else if(ch==')')break;
}
if(flag)now->date=-now->date;
if(!cnt&&!now->date){delete now;now=NULL;}//½Úµã²»´æÔÚ
return now;
}
void del(tree *p)
{
if(!p)return;
if(p->l)del(p->l);
if(p->r)del(p->r);
delete p;
p=NULL;
}
int dfs(tree *Root,int sum,int aim)
{
if(Root==NULL)return 0;
if(Root->l==NULL&&Root->r==NULL)
{
if(sum+Root->date==aim)return 1;
return 0;
}
if(dfs(Root->l,sum+Root->date,aim)+dfs(Root->r,sum+Root->date,aim))return 1;
return 0;
}
int main()
{
int n;
char ch;
tree *root;
//freopen("in.txt","r",stdin);
while(~scanf("%d",&n))
{
root=NULL;
while((ch=getchar())!=EOF)
{
if(ch=='('){root=built();break;}
}
if(dfs(root,0,n))printf("yes\n");
else printf("no\n");
del(root);
}
return 0;
}