难度:5
感觉给个难度5有点高了,这道题的输入有些别扭,但是用string还行,然后难点就在建树,因为点不是按照顺序给出来的,可能你的树深度为5,但是它给的是深度为7的点,也可能不需要到底,要把之前为了建别的点而建的点补充好,所以建树实际上就是四种情况,
首先因为个人习惯,先判断是不是到了null,这时分两种情况,操作做完了,这里插入就行,返回,另一种是操作还没有做完,还要接着向下递归,去建树,那么我们这个点还是要分配内存,把这个点建出来,但是没有值,所以赋值-1,表示这个点还没插入值,这是两种情况,
另外两种是,还没到null,一种是操作做完了,肯定要给这个节点赋值,然后返回,另一种是操作还没做完,那么还是要接着向下建树,这也是不那么特殊的情况。
所以总结一下就是操作做完没有两种情况,到没到null是两种情况,乘一下就是四种情况,操作做完那两种是要就地赋值然后结束,到了null肯定先要建一个点出来,怎么写应该都可以,
最后需要注意的是,这棵树不完整是两种,一是有的点没有插入值,就是我上面的-1,另一种就是这个点赋了多次值,这个建树的过程当中判断比较方便,上面那四种只有一种情况需要判断,
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;
struct node {
int data;
node *lchild, *rchild;
};
int ok = 1;
vi v;
void insert_t(node* &root, int x, string s) {
if (root == NULL) {
root = new node;
root->lchild = root->rchild = NULL;
if ((int) s.size() == 0){
root->data = x;
return;
} else {
root->data = -1;
}
} else if ((int) s.size() == 0) {
if (root->data != -1) ok = 0;
root->data = x;
return;
}
if (s[0] == 'L') insert_t(root->lchild, x, s.substr(1, (int) s.size() - 1));
else insert_t(root->rchild, x, s.substr(1, (int) s.size() - 1));
}
void bfs(node* root) {
queue<node*> q;
q.push(root);
while (!q.empty()) {
node* now = q.front();
q.pop();
if (now->data == -1) ok = 0;
v.pb(now->data);
if (now->lchild != NULL) q.push(now->lchild);
if (now->rchild != NULL) q.push(now->rchild);
}
}
int main() {
string s;
node* root = NULL;
while (cin >> s) {
if (s == "()") {
bfs(root);
if (ok) {
for (int i = 0; i < (int) v.size(); i++) {
cout << v[i] << (i < (int) v.size() - 1 ? " " : "\n");
}
} else cout << "not complete\n";
ok = 1;
v.clear();
root = NULL;
continue;
}
s.erase(s.begin());
s.erase(s.begin() + (int) s.size() - 1);
int t = s.find(',');
insert_t(root, stoi(s.substr(0, t)), s.substr(t + 1, (int) s.size() - t - 1));
}
return 0;
}