题目来源:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=48

Tree Summing 

Background

LISP was one of the earliest high-level programming languages and, with FORTRAN, is one of the oldest languages currently being used. Lists, which are the fundamental data structures in LISP, can easily be adapted to represent other important data structures such as trees.

This problem deals with determining whether binary trees represented as LISP S-expressions possess a certain property.

The Problem

Given a binary tree of integers, you are to write a program that determines whether there exists a root-to-leaf path whose nodes sum to a specified integer. For example, in the tree shown below there are exactly four root-to-leaf paths. The sums of the paths are 27, 22, 26, and 18.

Binary trees are represented in the input file as LISP S-expressions having the following form.


empty tree ::= ()

tree ::= empty tree (integer tree tree)

The tree diagrammed above is represented by the expression (5 (4 (11 (7 () ()) (2 () ()) ) ()) (8 (13 () ()) (4 () (1 () ()) ) ) )

Note that with this formulation all leaves of a tree are of the form (integer () () )

Since an empty tree has no root-to-leaf paths, any query as to whether a path exists whose sum is a specified integer in an empty tree must be answered negatively.

The Input

The input consists of a sequence of test cases in the form of integer/tree pairs. Each test case consists of an integer followed by one or more spaces followed by a binary tree formatted as an S-expression as described above. All binary tree S-expressions will be valid, but expressions may be spread over several lines and may contain spaces. There will be one or more test cases in an input file, and input is terminated by end-of-file.

The Output

There should be one line of output for each test case (integer/tree pair) in the input file. For each pair I,T (I represents the integer, Trepresents the tree) the output is the string yes if there is a root-to-leaf path in T whose sum is I and no if there is no path in T whose sum is I.

Sample Input

22 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
20 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
10 (3
(2 (4 () () )
(8 () () ) )
(1 (6 () () )
(4 () () ) ) )
5 ()

Sample Output

yes
no
yes
no 解题思路:
题目给出树一种定义表达式.每组数据给出目标数据target,以及树的结构表达式.要求判断所给的树中是否存在一条路径满足其上节点的和等于target,如果存在输出yes,否则输出no.
所给的树属于二叉树,但是不一定是满二叉树,所以对于所给的树进行左右递归计算,如果存在路径满足则输出yes,否则输出no
推荐博客1:http://www.cnblogs.com/devymex/archive/2010/08/10/1796854.html推荐博客2:http://blog.csdn.net/zcube/article/details/8545544推荐博客3:http://blog.csdn.net/mobius_strip/article/details/34066019

下面给出代码:

 #include <bits/stdc++.h>
#define MAX 100010 using namespace std; char Input()
{
char str;
scanf("%c",&str);
while(str == ' ' || str == '\n')
scanf("%c",&str);
return str;
} int work(int v,int *leaf)
{
int temp, value;
scanf("%d",&value);
temp = Input();
int max_num=,left=,right=;
if(temp == '(')
{
if(work(v-value,&left)) max_num=;
temp = Input();
if(work(v-value,&right)) max_num=;
temp = Input();
if(left&&right) max_num = (v == value);
}
else *leaf = ;
return max_num;
}
int main()
{
int n,temp;
while(~scanf("%d",&n))
{
Input();
if(work(n,&temp))
printf("yes\n");
else
printf("no\n");
}
return ;
}

其他方法:

 #include <iostream>
#include <string>
using namespace std;
//递归扫描输入的整棵树
bool ScanTree(int nSum, int nDest, bool *pNull) {
static int nChild;
//略去当前一级前导的左括号
cin >> (char&)nChild;
//br用于递归子节点的计算结果,bNull表示左右子是否为空
bool br = false, bNull1 = false, bNull2 = false;
//如果读入值失败,则该节点必为空
if (!(*pNull = ((cin >> nChild) == ))) {
//总和加上读入的值,遍例子节点
nSum += nChild;
//判断两个子节点是否能返回正确的结果
br = ScanTree(nSum, nDest, &bNull1) | ScanTree(nSum, nDest, &bNull2);
//如果两个子节点都为空,则本节点为叶,检验是否达到目标值
if (bNull1 && bNull2) {
br = (nSum == nDest);
}
}
//清除节点为空时cin的错误状态
cin.clear();
//略去当前一级末尾的右括号
cin >> (char&)nChild;
return br;
}
//主函数
int main(void) {
bool bNull;
//输入目标值
for (int nDest; cin >> nDest;) {
//根据结果输出yes或no
cout << (ScanTree(, nDest, &bNull) ? "yes" : "no") << endl;
}
return ;
}

使用栈解决的代码:

 #include <stdio.h>
#include <string.h>
#define MAXN 10000 int stack[MAXN];
int topc, top, t; bool judge() {
int sum = ;
for (int i=; i<=top; i++)
sum += stack[i];
if (sum == t)
return true;
return false;
} int main() { //freopen("f:\\out.txt", "w", stdout);
while (scanf("%d", &t) != EOF) {
int tmp = , flag = , isNeg = ;
char pre[];
topc = top = ;
memset(pre, , sizeof (pre)); while () {
// 接收字符的代码,忽略掉空格和换行
char ch = getchar();
while ('\n'==ch || ' '==ch)
ch = getchar(); // 记录该字符前三个字符,便于判断是否为叶子
pre[] = pre[];
pre[] = pre[];
pre[] = pre[];
pre[] = ch; // 如果遇到左括弧就进栈
if ('(' == ch) {
topc++;
if (tmp) {
if (isNeg) {
tmp *= -;
isNeg = ;
}
stack[++top] = tmp;
tmp = ;
}
continue;
} // 如果遇到右括弧就出栈
if (')' == ch) {
// 如果为叶子便计算
if ('('==pre[] && ')'==pre[] && '('==pre[]) {
if (!flag)
flag = judge();
}
else if (pre[] != '('){
top--;
}
topc--;
// 如果左括弧都被匹配完说明二叉树输入完毕
if (!topc)
break;
continue;
}
if ('-' == ch)
isNeg = ;
else
tmp = tmp* + (ch-'');
} if (flag)
printf("yes\n");
else
printf("no\n");
} return ;
}

UVa 112 - Tree Summing(树的各路径求和,递归)的更多相关文章

  1. UVa 112 Tree Summing

    题意: 计算从根到叶节点的累加值,看看是否等于指定值.是输出yes,否则no.注意叶节点判断条件是没有左右子节点. 思路: 建树过程中计算根到叶节点的sum. 注意: cin读取失败后要调用clear ...

  2. POJ 题目1145/UVA题目112 Tree Summing(二叉树遍历)

    Tree Summing Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 8132   Accepted: 1949 Desc ...

  3. Codeforces 618D Hamiltonian Spanning Tree(树的最小路径覆盖)

    题意:给出一张完全图,所有的边的边权都是 y,现在给出图的一个生成树,将生成树上的边的边权改为 x,求一条距离最短的哈密顿路径. 先考虑x>=y的情况,那么应该尽量不走生成树上的边,如果生成树上 ...

  4. [转] Splay Tree(伸展树)

    好久没写过了,比赛的时候就调了一个小时,差点悲剧,重新复习一下,觉得这个写的很不错.转自:here Splay Tree(伸展树) 二叉查找树(Binary Search Tree)能够支持多种动态集 ...

  5. 【数据结构】B-Tree, B+Tree, B*树介绍 转

    [数据结构]B-Tree, B+Tree, B*树介绍 [摘要] 最近在看Mysql的存储引擎中索引的优化,神马是索引,支持啥索引.全是浮云,目前Mysql的MyISAM和InnoDB都支持B-Tre ...

  6. 洛谷P2633/bzoj2588 Count on a tree (主席树)

    洛谷P2633/bzoj2588 Count on a tree 题目描述 给定一棵N个节点的树,每个点有一个权值,对于M个询问(u,v,k),你需要回答u xor lastans和v这两个节点间第K ...

  7. UVA.548 Tree(二叉树 DFS)

    UVA.548 Tree(二叉树 DFS) 题意分析 给出一棵树的中序遍历和后序遍历,从所有叶子节点中找到一个使得其到根节点的权值最小.若有多个,输出叶子节点本身权值小的那个节点. 先递归建树,然后D ...

  8. POJ 1145 Tree Summing

    Tree Summing Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 7698   Accepted: 1737 Desc ...

  9. easyUI之Tree(树)

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...

随机推荐

  1. AngularJS的学习--TodoMVC的分析

    最近一段时间一直在看AngularJS,趁着一点时间总结一下. 官网地址:http://angularjs.org/ 先推荐几个教程 1. AngularJS入门教程 比较基础,是官方Tutorial ...

  2. 利用PS自动切图、支持svg且支持icoMoon——再也不用四处去转格式了

    今天想导出svg格式的图片支持webFont,结果AI打不开了,文件好像损坏了,于是就想办法在PS里面导出. 网上搜索到一篇文章,腾讯的 http://isux.tencent.com/ps-phot ...

  3. redis在centOS的安装

    1.安装tcl支持 yum install tcl 2.安装redis我们以最新的2.8.9为例 $ wget http://download.redis.io/releases/redis-2.8. ...

  4. 【Spark】---- Spark 硬件配置

    存储系统 Spark任务需要从一些外部的存储系统加载数据(如:HDFS 或者 HBase),重要的是存储系统要接近Spark系统,我们有如下推荐:   (1)如果可能,运行Spark在相同的HDFS节 ...

  5. Java集合Iterator迭代器的实现

    一.迭代器概述 1.什么是迭代器? 在Java中,有很多的数据容器,对于这些的操作有很多的共性.Java采用了迭代器来为各种容器提供了公共的操作接口.这样使得对容器的遍历操作与其具体的底层实现相隔离, ...

  6. C#调用NPOI组件读取excel表格数据转为datatable写入word表格中并向word中插入图片/文字/书签 获得书签列表

    调用word的com组件将400条数据导入word表格中耗时10分钟简直不能忍受,使用NPOI组件耗时4秒钟.但是NPOI中替换书签内容的功能不知道是不支持还是没找到. 辅助类 Excel表格数据与D ...

  7. 常用库nuget包集合

    ColorConsole htmlagilitypack.1.4.9.5 经测试效率比 CsQueryLaster 高 csvhelper Extend Devlib系列一套 itextsharp l ...

  8. csharp: SDK:CAPICOM

    http://www.microsoft.com/zh-cn/download/details.aspx?id=25281 //************************************ ...

  9. jdbcTemplate queryForObject 查询 结果集 数量

    1.组织sql语句, 查询参数 数组, 设置返回类型 public int countByCondtion(String title, int mediaType, String currentSta ...

  10. RAID选项

    RAID:Redundant Array Independent Disk(独立磁盘构成的具有冗余能力的阵列) 最常见的为RAID类型为:0,1,5和10:3和6很少见,但在某些环境中仍然有用. RA ...