感觉这个题目就是在考察非递归先序建树,首先将所有的数据全部读入进来,然后利用栈非递归建树。将根节点所在的标志记为0,如果同时如果从当前节点向左,则相应的标志减一,如果是向右,则相应的标志加一,同时建立相应的标志到该标志的“总数”的映射,最后输出即可。对每个节点,设置一个pos,来记录相应的标志,具体的实现见源代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<sstream>
using namespace std;
typedef struct node{
int val;
struct node* left, *right;
int pos;
node(int value){
val = value;
left = NULL;
right = NULL;
}
}node;
int main(){
string s;
map<int, int> in2in;
int Case = 0;
stack<node*> st;
int pos;
vector<int> data;
while (getline(cin, s)){
if (s == "-1") break;
stringstream ss(s);
int t;
while (ss >> t){
data.push_back(t);
}
}
int position = 0;
while (position < data.size()){
pos = 0;
node* root = new node(data[position]);
root->pos = 0;
st.push(root);
in2in[pos] = data[position];
position++;
int length = data.size();
while (position < length && !st.empty()){
node *temp = st.top();
pos = temp->pos;
while (data[position] != -1){
temp->left = new node(data[position]);
temp = temp->left;
pos--;
temp->pos = pos;
if (in2in.find(pos) == in2in.end()) in2in[pos] = data[position];
else in2in[pos] += data[position];
position++;
st.push(temp);
}
position++;
while (position < length&&data[position] == -1){
st.pop();
if (st.empty()) break;
temp = st.top();
position++;
pos = temp->pos;
}
if (position < length&&data[position] != -1){
st.pop();
temp->right = new node(data[position]);
temp = temp->right;
pos++;
temp->pos = pos;
if (in2in.find(pos) == in2in.end()) in2in[pos] = data[position];
else in2in[pos] += data[position];
st.push(temp);
position++;
}
}
Case++;
cout << "Case " << Case << ":" << endl;
for (auto it = in2in.begin(); it != in2in.end();){
cout << it->second;
it++;
if (it != in2in.end()) cout << " ";
}
cout << endl << endl;
in2in.clear();
position++;
}
//system("pause");
return 0;
}