UVa 112 - Tree Summing(树的各路径求和,递归)
| 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(树的各路径求和,递归)的更多相关文章
- UVa 112 Tree Summing
题意: 计算从根到叶节点的累加值,看看是否等于指定值.是输出yes,否则no.注意叶节点判断条件是没有左右子节点. 思路: 建树过程中计算根到叶节点的sum. 注意: cin读取失败后要调用clear ...
- POJ 题目1145/UVA题目112 Tree Summing(二叉树遍历)
Tree Summing Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 8132 Accepted: 1949 Desc ...
- Codeforces 618D Hamiltonian Spanning Tree(树的最小路径覆盖)
题意:给出一张完全图,所有的边的边权都是 y,现在给出图的一个生成树,将生成树上的边的边权改为 x,求一条距离最短的哈密顿路径. 先考虑x>=y的情况,那么应该尽量不走生成树上的边,如果生成树上 ...
- [转] Splay Tree(伸展树)
好久没写过了,比赛的时候就调了一个小时,差点悲剧,重新复习一下,觉得这个写的很不错.转自:here Splay Tree(伸展树) 二叉查找树(Binary Search Tree)能够支持多种动态集 ...
- 【数据结构】B-Tree, B+Tree, B*树介绍 转
[数据结构]B-Tree, B+Tree, B*树介绍 [摘要] 最近在看Mysql的存储引擎中索引的优化,神马是索引,支持啥索引.全是浮云,目前Mysql的MyISAM和InnoDB都支持B-Tre ...
- 洛谷P2633/bzoj2588 Count on a tree (主席树)
洛谷P2633/bzoj2588 Count on a tree 题目描述 给定一棵N个节点的树,每个点有一个权值,对于M个询问(u,v,k),你需要回答u xor lastans和v这两个节点间第K ...
- UVA.548 Tree(二叉树 DFS)
UVA.548 Tree(二叉树 DFS) 题意分析 给出一棵树的中序遍历和后序遍历,从所有叶子节点中找到一个使得其到根节点的权值最小.若有多个,输出叶子节点本身权值小的那个节点. 先递归建树,然后D ...
- POJ 1145 Tree Summing
Tree Summing Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 7698 Accepted: 1737 Desc ...
- easyUI之Tree(树)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...
随机推荐
- Gulp.js - 简单、直观的自动化项目构建工具
Gulp.js 是一个简单.直观的构建系统.崇尚代码优于配置,使复杂的任务更好管理.通过结合 NodeJS 的数据流的能力,你能够快速构建.通过简单的 API 接口,只需几步就能搭建起自己的自动化项目 ...
- [python]逆水行舟不进则退(1)
工作后迎来的第一个长假期,打算在家休息一下,看看书之类的.但是不写点东西,不做点东西,感觉有些浪费时间.同时也想通过做点东西检验下自己这段时间的收获.其实在我开始写这篇文章的时候心里还是很没底的-交代 ...
- Android SQLite的ORM接口实现(一)---findAll和find的实现
最近在看Android的ORM数据库框架LitePal,就想到可以利用原生的SQLite来实现和LitePal类似的ORM接口实现. LitePal有一个接口是这样的: List<Status& ...
- Jquery几个比较实用,但又让很多人忽略的几个函数
工作中接触的人中,这些函数的使用频率比较少,我用的又比较好用的几个函数 来给大家分享一下. 你有你喜欢的,也可以分享一下 1.filter 使用了我要什么就有什么 这个函数不但可以很方便的筛选自定义H ...
- sitemesh学习笔记(2)
之前我也是通过网上一些资料来学习sitemesh的,后来发现那些资料都比较老了,现在最近的已经是sitemesh3了而我之前看的是sitemesh2.3,今天重新去看了一些sitemesh3的资料,发 ...
- Entity Framework优缺点及使用方法总结
Entity Framework是M$提供的一个ORM框架,它旨在为小型应用程序中数据层的快速开发提供便利. nuget上185W多的下载量,说明.Net开发人员还是比较喜欢用EF的.但是EF在提供了 ...
- ActiveMQ学习(一)——MQ的基本概念
1) 队列管理器 队列管理器是MQ系统中最上层的一个概念,由它为我们提供基于队列的消息服务. 2) 消息 在MQ中,我们把应用程序交由MQ传输的数据定义为消息,我们可以定义消息的内容并对消息进行广义的 ...
- DZNEmptyDataSet,优秀的空白页或者出错页封装
简介 项目主页:https://github.com/dzenbot/DZNEmptyDataSet 提示:主要用于UITableView和UICollectionView,也可以用于UIScroll ...
- C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限
C#修改文件或文件夹的权限,为指定用户.用户组添加完全控制权限 public void SetFileRole(string foldPath) { DirectorySecurity fsec = ...
- [爬虫学习笔记]Url过滤模块UrlFilter
Url Filter则是对提取出来的URL再进行一次筛选.不同的应用筛选的标准是不一样的,比如对于baidu/google的搜索,一般不进行筛选,但是对于垂直搜索或者定向抓取的应用,那 ...