题目链接:https://vjudge.net/problem/UVA-122
题解:题意就是按题目要求建立二叉树,然后进行BFS,我在uDebug上进行了测试,都通过了,但是仍然没法通过vjudge上的测试例,找不到问题在哪儿?希望有大神能帮助看看,多谢,多谢。
代码:(注意没有AC)
#include<iostream>
#include<cstdio>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<sstream>
#include<vector>
using namespace std;
struct node {
int data = -1;
node *left = NULL;
node *right = NULL;
};
node * root = new node();
string dir_s;
string s;
bool insert(node *r, int value, char dir, int remain) {
if (remain == -1) {
if (r->data != -1)return false;
r->data = value;
}
else {
if (dir == 'L') {
if (r->left == NULL)r->left = new node();
}
else {
if (r->right == NULL)r->right = new node();
}
return insert(dir == 'L' ? r->left : r->right, value, dir_s[dir_s.length() - remain ], remain - 1);
}
return true;
}
queue<node> q;
void clear() {
while (!q.empty()) {
q.pop();
}
root = new node();
}
int main() {
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
int flag = 1;
while (cin>>s) {
if (s == "()"||flag==0) {
vector<int> v;
q.push(*root);
while (!q.empty()) {
node p = q.front(); q.pop();
if (p.data == -1) {
flag = 0;
break;
}
v.push_back(p.data);
if (p.left != NULL)q.push(*p.left);
if (p.right != NULL)q.push(*p.right);
}
if (flag == 0)cout <<"not complete";
else {
for (int i = 0; i < v.size()-1; i++)cout << v[i] << " ";
cout << v[v.size() - 1];
}
cout << endl;
//print
clear();
flag = 1;
continue;
}
else {
dir_s = s.substr(s.find_first_of(',') + 1, (s.find_first_of(')') - s.find_first_of(',')) - 1);
string num = s.substr(1,s.find_first_of(',')-1);
stringstream ss(num);
int nu = 0;
ss >> nu;
flag=insert(root, nu, dir_s[0], dir_s.length() - 1);
}
}
return 0;
}