照着书写得一脸懵逼也是醉了。。。意识到掌握语言的技巧的重要性,sscanf大法好,new大法好。
还有为什么加了remove就不对了。。。爆内存之类的,刘汝佳老师求解释
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
bool failed;
//节点类型
struct Node{
bool have_value; //是否被赋值过
int v; //节点值
Node *left, *right;
Node():have_value(false),left(NULL),right(NULL){} //构造函数
};
Node* root; //二叉树的根节点
Node* newnode() { return new Node(); }
void remove_tree(Node* u) {
if(u == NULL) return;
remove_tree(u->left);
remove_tree(u->right);
delete u;
}
void addnode(int v, char* s){
int n = strlen(s);
//remove_tree(root);
Node* u = root; //从根节点往下走
for(int i = 0; i < n; i++)
if(s[i] == 'L'){
if(u->left == NULL) u->left = newnode(); //节点不存在,建立新节点
u = u->left; //往左走
}
else if(s[i] == 'R'){
if(u->right == NULL) u->right = newnode();
u = u->right;
} //忽略其他情况,即最后多余的那个右括号
if(u->have_value) failed = true; //已经赋过值,表明输入有误
u->v = v;
u->have_value = true; //做标记
}
char s[1000]; //保存读入节点
bool read_input(){
failed = false;
root = newnode(); //创建根节点
for(;;){
if(scanf("%s", s) != 1) return false; //整个输入结束
if(!strcmp(s, "()")) break; //结束标志,退出循环
int v;
sscanf(&s[1], "%d", &v); //读入节点值
addnode(v, strchr(s, ',')+1); //查找逗号然后插入节点
}
return true;
}
bool bfs(vector<int>& ans){
queue<Node*> q;
ans.clear();
q.push(root);
while(!q.empty()){
Node* u = q.front();
q.pop();
if(!u->have_value) return false;
ans.push_back(u->v);
if(u->left != NULL) q.push(u->left);
if(u->right != NULL) q.push(u->right);
}
return true;
}
int main(){
freopen("level.in", "r", stdin);
freopen("level.out", "w", stdout);
vector<int> ans;
while(read_input()){
if(failed||!bfs(ans)){
printf("not complete\n");
}
else{
int t = ans.size();
for(int i = 0; i < t; i++){
if(i) printf(" ");
printf("%d",ans[i]);
}
printf("\n");
}
}
return 0;
}