题解:这道题在建树时要把位置的参数传递以更新每叠叶子的和,题目中有说明叠数不会超过80,就从位置40开始把和存到数组。
#include <stdio.h>
#include <string.h>
const int N = 85;
struct Node {
int val;
Node* left;
Node* right;
Node () {
val = -1;
left = right = NULL;
}
};
int ans1[N], ans2[N];
Node* build(int pos, int a) {
int n;
char c;
Node* node = new Node;
scanf("%d%c", &n, &c);
if(n != -1) {
node -> val = n;
ans1[pos] += n;
node -> left = build(pos - 1, 1);
node -> right = build(pos + 1, 2);
}
else {
if (a == 1)
pos += 1;
else if (a == 2)
pos -= 1;
return NULL;
}
return node;
}
void Delete(Node* node) {
if (node == NULL)
return;
if (node -> left != NULL)
Delete(node -> left);
if (node -> right != NULL)
Delete(node -> right);
delete node;
}
int main() {
int cases = 1;
char c;
Node* root;
while (1) {
memset(ans1, 0, sizeof(ans1));
root = build(40, 0);
if (root == NULL)
break;
else {
printf("Case %d:\n", cases++);
int k = 0;
for (int i = 0; i < N; i++)
if (ans1[i] > 0) {
ans2[k++] = ans1[i];
}
for (int i = 0; i < k - 1; i++)
printf("%d ", ans2[i]);
printf("%d\n\n", ans2[k - 1]);
Delete(root);
}
}
return 0;
}