原题链接:https://vjudge.net/problem/UVA-122
分类:树
备注:二叉树的动态创建与BFS
通过该题复习了一下指针。其实能避免用指针还是尽量避免,本来做题很少用指针,不熟地使用指针就是很容易出错。
注意点:每次出现新结点必须要申请新空间,new申请空间可以用构造函数,读入时得一次性读完,不然操作可能出现问题。
代码如下:
#include<cstdio>
#include<vector>
#include<string>
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 1000 + 5;
vector<int>ans;
bool failed;
struct node {
int value;
bool hav_value;
node* Left, * Right;
};
node* root = new node;
void built(int value, string sub) {
node *tmp = root;
for (int i = 0; i < sub.length() - 1; i++) {
if (sub[i] == 'L') {
if (tmp->Left == NULL) {
tmp->Left = new node;
tmp->Left->hav_value = false;
tmp->Left->Left = tmp->Left->Right = NULL;
}
tmp = tmp->Left;
}
else if (sub[i] == 'R') {
if (tmp->Right == NULL) {
tmp->Right = new node;
tmp->Right->hav_value = false;
tmp->Right->Left = tmp->Right->Right = NULL;
}
tmp = tmp->Right;
}
}
if (tmp->hav_value)failed = true;
tmp->hav_value = true;
tmp->value = value;
}
bool read() {
failed = false;
root->Left = root->Right = NULL;
root->hav_value = false;
ans.clear();
string s;
while (1) {
if (!(cin >> s))return false;
if (s == "()")break;
int pos = s.find(',', 0);
int value = 0;
for (int i = 1; i < pos; i++)
value = (value << 1) + (value << 3) + s[i] - '0';
built(value, s.substr(pos + 1));
}
return true;
}
bool bfs() {
node *head = root;
queue<node*>q;
q.push(head);
while (!q.empty()) {
head = q.front(); q.pop();
if (!head->hav_value)return false;
ans.push_back(head->value);
if (head->Left != NULL)q.push(head->Left);
if (head->Right != NULL)q.push(head->Right);
}
return true;
}
int main(void) {
while (read()) {
if (failed || !bfs()) {
printf("not complete\n");
continue;
}
else {
for (int i = 0; i < ans.size(); i++)
printf("%d%c", ans[i], i == ans.size() - 1 ? '\n' : ' ');
}
}
return 0;
}