这道题就比较简单了,借助足够大的数组保存每个位置的值得总和就好。其实做完之后感觉建树反而显得冗余,因为我的代码是边读入边判断的,树结构其实没有实际的用处,只是在计算总和时顺便建好的,所以不建树可能是更好的方法(参照紫书)。当然如果是建好树后再遍历求结果的话树结构是有用的,但是很显然会复杂很多。
题目链接:UVa 699
AC代码:
#include <iostream>
#include <cstring>
//#include <fstream>
using namespace std;
const int maxn = 1000;
struct Node{
Node* left, * right;
Node() :left(NULL), right(NULL) {}
}*root;
int sum[maxn];
void remove(Node* u) {
if (u == NULL) return;
remove(u->left);
remove(u->right);
delete u;
}
Node* build(Node* node,int pos) {
node = new Node();
int x;
cin >> x;
if (x == -1) return NULL;
sum[pos] += x;
node->left = build(node->left, pos - 1);
node->right = build(node->right, pos + 1);
return node;
}
bool Init() {
int v;
cin >> v;
if (v == -1) return false;
int pos = maxn / 2;
memset(sum, 0, sizeof(sum));
remove(root);
root = new Node();
sum[pos] = v;
root->left=build(root->left, pos - 1); //建立左右子树
root->right=build(root->right, pos + 1);
return true;
}
int main() {
//ofstream out("C:\\Users\\Acer\\Desktop\\1.txt");
int cnt = 1;
while (Init()) {
int p = 0;
//if (out.is_open()) {
while (sum[p] == 0) p++;
cout << "Case " << cnt++ << ":" << endl << sum[p++];
while (sum[p] != 0)
cout << " " << sum[p++];
cout << endl<<endl;
//}
}
return 0;
}
记录紫书代码:
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 1000;
int sum[maxn];
void build(int p) {
int v;
cin >> v;
if (v == -1) return;
sum[p] += v;
build(p - 1);
build(p + 1);
}
bool init() {
int v;
cin >> v;
if (v == -1) return false;
int pos = maxn / 2;
memset(sum, 0, sizeof(sum));
sum[pos] = v;
build(pos - 1); build(pos + 1);
return true;
}
int main() {
int cnt = 1;
while (init()) {
int p = 0;
while (sum[p] == 0) p++;
cout << "Case " << cnt++ << ":" << endl << sum[p++];
while (sum[p] != 0)
cout << " " << sum[p++];
cout << endl << endl;
}
return 0;
}