uva112 Tree Summing(二叉树 + 栈)
来源:互联网 发布:如何在淘宝提高销量 编辑:程序博客网 时间:2024/05/22 07:00
题意:LISP 列表语言实现二叉树, 构树方式对照图就可知道, 叶子后面都有两个()。 给定一个数target, 求此树中是否有一条路径(从root到叶子), 它上面的结点总和等于target, 如果存在 输出yes, 否则输出no。
思路:这道题可以不用建树。只要读到叶子结点的时候, 把这条路的sum 跟 target比较, 相等就ok = true。 如何读? 读到( 入栈staSign, 读到数值, 入栈staNum, 读到)的时候staSign 跟 staNum各出栈(当然情况没那么简单, 如果读入空括号怎么办? 判断两栈的size是否相等。), 用count统计连续读入的空括号数, count == 2 的时候, 自然是到了叶子结点。 这道题 难点还在于输入处理, 用getchar() 一个字符一个字符的读入。遇到数字的组成部分就保存在字符里, 然后sscanf()
算法复杂度:o(n)n是字符数。
代码:
uva112_.cpp AC后重写的。
#include <cstdio>#include <cstring>#include <stack>#include <cctype>using namespace std;#define NUM_BIT 100int main(){int target;stack<char> staSign;stack<int> staNum;bool ok;char last;int count;char strNum[NUM_BIT];char *p;while (scanf("%d", &target) == 1) {// init while (!staSign.empty()) {staSign.pop();}while (!staNum.empty()) {staNum.pop();}ok = false;last = '\0';count = 0;memset(strNum, 0, sizeof(strNum));p = strNum;// enter treechar ch;while (ch = getchar()) {if (isdigit(ch) || ch == '(' || ch == ')' || ch == '-') {if (ch == '(') {staSign.push(ch);if (isdigit(last)) {int num;sscanf(strNum, "%d", &num);if (!staNum.empty()) {num += staNum.top();}staNum.push(num);memset(strNum, 0, sizeof(strNum));p = strNum;}} else if (isdigit(ch) || ch == '-') {*p++ = ch;count = 0;} else if (ch == ')') {if (staNum.size() != staSign.size()) {count++;if (!staNum.empty() && count == 2 && staNum.top() == target) {ok = true;}} else {staNum.pop();}staSign.pop();if (staSign.empty()) {break;}}last = ch;}}if (ok) {printf("yes\n");} else {printf("no\n");}}return 0;}
- uva112 Tree Summing(二叉树 + 栈)
- UVA112-Tree Summing
- uva112 - Tree Summing
- UVA112 Tree Summing
- uva112 Tree Summing
- uva112-Tree Summing[动态建树]
- 二叉树专题 Tree Summing
- UVA 112 & POJ 1145 Tree Summing(数据结构,二叉树,栈)
- 【二叉树】UVA112
- poj 1145Tree Summing +dfs+二叉树
- POJ-Tree Summing【递归】【二叉树】【好题】
- UVa 112 - Tree Summing 二叉树构造, 二叉树路径和
- 树uva112
- Tree summing -没用树,栈堆直接推演
- Tree Summing
- UVa 112 Tree Summing (scanf()去空格&递归&二叉树遍历)
- Tree Summing - UVa 112 简单二叉树(丧病的数据输入)
- POJ 题目1145/UVA题目112 Tree Summing(二叉树遍历)
- MFC单文档中嵌入CEF(Chromium Embedded Framework)使用多进程
- 我的知识管理工具列表
- Aspose Word模板使用总结
- WINCE Activesync 同步问题
- 使用connect by、Sys_Connect_By_Path实现的SQL
- uva112 Tree Summing(二叉树 + 栈)
- web aria 例子
- java中常用的时间处理类TimeUtil
- Unity3D 碰撞
- 2013年 天朝程序员薪资等级
- Interleaving String
- android圆角按钮的背景
- 归并排序
- 2012中国云实践之企业总评榜