UVa 112 - Tree Summing

来源:互联网 发布:sass for mac 安装 编辑:程序博客网 时间:2024/05/22 12:33
//利用二叉树的递归定义进行递归访问, AC:0.069s#include <iostream>#include <cstdio>#include <cstring>#include <cctype>using namespace std;int found; //是否找到int sum;   //记录树根到当前节点的路径总和int n;     //需要判断的值//跳过下一个非空字符void get_next(){    char ch;    while(true) {        ch = getchar();        if(isspace(ch)) continue; //跳过space,\n        return;    }}// return 0:空树, 1:非空树int get_tree(){    while(true) {        get_next(); // (        int val;        if(scanf("%d", &val) != 1) {get_next(); return 0;} //空树        sum += val;        int left = get_tree();  //遍历左子树        int right = get_tree(); //遍历右子树        if(!left && !right && sum==n) {found = true;} //是叶子节点 且满足条件        get_next(); // )        sum -= val; // 深度减小        return 1;    }}int main(){    #ifndef ONLINE_JUDGE    freopen("in.txt", "r", stdin);    #endif    while(scanf("%d", &n) == 1)    {        sum = 0;        found = false;        get_tree();        if(found) printf("yes\n");        else printf("no\n");    }}