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 ...
随机推荐
- ASP.NET MVC3 在_ViewStart設定Layout後用RenderAction的注意事項
ASP.NET MVC3 在_ViewStart設定Layout後用RenderAction的注意事項 3/24 TW MVC第一次活動圓滿的結束了,雖然是RC,但也來了不少願意聽我們分享的好朋友. ...
- HMM 自学教程(二)生成模型
本系列文章摘自 52nlp(我爱自然语言处理: http://www.52nlp.cn/),原文链接在 HMM 学习最佳范例,这是针对 国外网站上一个 HMM 教程 的翻译,作者功底很深,翻译得很精彩 ...
- Pattern Lab - 构建先进的原子设计系统
Pattern Lab 是一个工具集,帮助您创建原子设计系统.在它的核心,是一个自定义静态网站生成器,构建了类似原子,分子和界面结合在一起,形成模板和页面.Pattern Lab 可以作为项目的模式库 ...
- [mysql]去重:DISTINCT
SELECT DISTINCT name, age:去掉name字段重复的(需要先写去重的字段):如果想多个取出多个字段重复,需要用group by.
- 查找表或其他对象在某个Server上的存在
EXEC sp_MSforeachdb 'use ? ; IF EXISTS(SELECT top 1 1 FROM sys.syscomments WHERE text LIKE ''%test% ...
- dp --- 2014 Asia AnShan Regional Contest --- HDU 5074 Hatsune Miku
Hatsune Miku Problem's Link: http://acm.hdu.edu.cn/showproblem.php?pid=5074 Mean: 有m种音符(note),现在要从 ...
- 组合数学 - 母函数的运用 + 模板 --- hdu : 2082
找单词 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submiss ...
- 重构第23天 引用参数对象(Introduce Parameter Object)
理解:有时候我们的一个方法,需要很多个参数,太多参数,不易阅读和理解,我们就可以把多个参数封装成一个对象. 详解: 重构前代码: public class Registration { public ...
- mysql数据库入门
在很多地方都有人提到MySQL这个数据,之前没有接触过的mysql数据库的童鞋们可以跟我一起走进mysql的世界. http://hovertree.com/menu/mysql/ 安装我就不多说了, ...
- 安装jdk For Windows
1.下载JDK查看最新:http://www.oracle.com/technetwork/java/javase/downloads/index.html根据操作系统选择合适的JDK进行下载2.运行 ...