知识点:二叉树遍历
这个题就是先序递归输入二叉树,我们可以直接递归输入的时候统计答案,然后需要注意,我们要先解决完左子树,然后才是右子树,
这道题就是我们根据二叉树的逻辑结构,走了一遍先序遍历,但是不用建树就得到了答案,
#include <bits/stdc++.h>
using namespace std;
map<int, int> mp;
void solve(int x, int ind) {
mp[ind] += x;
int a, b;
cin >> a;
if (a != -1) {
solve(a, ind - 1);
}
cin >> b;
if (b != -1) {
solve(b, ind + 1);
}
}
int main() {
int T = 1;
int x;
while (cin >> x && x != -1) {
cout << "Case " << T++ << ":\n";
solve(x, 0);
int ok = 0;
for (map<int, int>::iterator it = mp.begin(); it != mp.end(); it++) {
if (ok++) cout << " ";
cout << it->second;
}
cout << "\n\n";
mp.clear();
}
return 0;
}