题目大意:给一个数和一棵树问是否有一叶子到根的值为该数。
解题思路:递归,若当前节点无孩子(叶子)则判断和是否为所需数字。结束后需将尾部反括号读入以免影响下一个样例。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<ctype.h>
using namespace std;
int n;
void read() {
char c;
c = getchar();
while (c != '(' && c != ')')
c = getchar();
}
int dfs(int tot, int *leaf) {
int tmp, tag = 0, l = 0, r = 0;
read();
if (scanf("%d", &tmp)) {
*leaf = 1;
tot += tmp;
if (dfs(tot, &l)) tag = 1;
if (dfs(tot, &r)) tag = 1;
if (!l && !r)
if (n == tot) tag = 1;
else tag = 0;
}
read();
return tag;
}
int main() {
while (scanf("%d", &n) != EOF) {
int t = 1;
if (dfs(0, &t)) printf("yes\n");
else printf("no\n");
}
return 0;
}