您的位置:首页 > 其它

UVa 112 - Tree Summing

2013-05-01 21:43 381 查看
//利用二叉树的递归定义进行递归访问, 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");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: