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;}


原创粉丝点击