uva112 Tree Summing(二叉树 + 栈)
2013-07-26 21:20
267 查看
题意: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后重写的。
思路:这道题可以不用建树。只要读到叶子结点的时候, 把这条路的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 100 int 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 tree char 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; }
相关文章推荐
- UVA 112 & POJ 1145 Tree Summing(数据结构,二叉树,栈)
- UVa 112 - Tree Summing 二叉树构造, 二叉树路径和
- Tree Summing - UVa 112 简单二叉树(丧病的数据输入)
- UVA 112 - Tree Summing
- uva oj 112 - Tree Summing
- uva 112 Tree Summing
- UVA 112-Tree Summing
- UVa 112 Tree Summing
- 数据结构 uva 112-Tree Summing
- UVA 112 - Tree Summing(栈)
- UVA_112_Tree Summing
- UVA - 112 Tree Summing
- UVa 112 - Tree Summing
- UVa 112 - Tree Summing
- POJ 题目1145/UVA题目112 Tree Summing(二叉树遍历)
- UVA112二叉树之使用标记忽略空格和回车
- poj 1145 (uva 112) Tree Summing
- UVa 112 - Tree Summing
- UVA - 112 - Tree Summing (数的求和!栈的应用!)
- uva 112 Tree Summing