题目来源: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. 使用命令行备份指定文件夹并保留最新N份

    客户需要对网站进行定期备份,并保留最近30天的文件,编写后以下脚本,通过Windows的任务计划进行调度 对比手工和任务计划调度运行情况来看,手工运行中可直接调用RAR.exe和网络进行传输,但是任务 ...

  2. sitemesh学习笔记(1)

    最近在学习web开发的时候,发现很多的页面都存在同样的导航栏,登陆栏,js,jQuery等等相同的元素.这样就感觉开发变得好臃肿啊,并且,有时候改一个元素,就要把所有包含这个元素的页面全部重新码一遍, ...

  3. 关于开发Windows服务程序容易搞混的地方!

    在开发Windows服务程序时,我们一般需要添加安装程序,即:serviceInstaller,里面有几个关于名称属性,你都搞明白了吗? 1.Description:表示服务说明(描述服务是干什么的) ...

  4. 算法解读:s变量和数组

    算法是解决问题并获得结果的过程.在这个处理过程中,问题以数据的形式输入,结果同样以数据的形式输出,在算法的处理过程中,也需要各种临时的数据. 数据是什么? 数据是多种不同信息的表现. 以料理中的食谱为 ...

  5. SQL 批量字符串替换

    --在SQL SERVER中批量替换字符串的方法 update table[表名] set Fields[字段名]=replace(Fields[字段名],'被替换原内容','要替换成的内容') up ...

  6. 【WP8.1】富文本

    之前写过一篇WP8下的富文本的文章,但是写的不是很好,整理了一下,分享一下WP8.1下的富文本处理 富文本处理主要是对表情和链接的处理,一般使用RichTextBlock进行呈现 问题说明: 由于Ri ...

  7. Sql发布订阅设置不初始化订阅库架构的设置

    参考:http://www.cnblogs.com/TeyGao/p/3521231.html

  8. Winform屏幕截图保存C#代码

    代码如下: using System.Runtime.InteropServices; using System.Drawing.Imaging; [System.Runtime.InteropSer ...

  9. [CLR via C#]9. 参数

    一.可选参数和命名参数 在设计一个方法的参数时,可为部分或全部参数分配默认值.然后,调用这些方法的代码时可以选择不指定部分实参,接受默认值.此外,调用方法时,还可以通过指定参数名称的方式为其传递实参. ...

  10. 重新想象 Windows 8.1 Store Apps (73) - 新增控件: DatePicker, TimePicker

    [源码下载] 重新想象 Windows 8.1 Store Apps (73) - 新增控件: DatePicker, TimePicker 作者:webabcd 介绍重新想象 Windows 8.1 ...