Uva--122 Trees on the level(二叉树的层次遍历)
记录
23:27 2023-4-20
https://onlinejudge.org/external/1/122.pdf
reference:《算法竞赛入门经典第二版》例题6-7
二叉树的层次遍历,这里是直接复制了作者的代码。(之前在我的数据结构学习里面手写过树、二叉树、AVL树(说是手写,其实也是照着浙大那个数据结构公开课,参考书是Data Structures and Algorithm Analysis in C/C++/JAVA),前序中序后序也都实现过) 遗憾的是,书上有些内容课程是没有讲到的(毕竟是主要讲数据结构),后面我也没把它看完,刚粗略看了下,没看过的有第九章图论算法的网络流和深度优先搜索的应用、第十章算法设计技巧、第十一章摊还分析、第十二章高级数据结构及其实现(红黑树在这,所以我没看:( ),这些内容还是有必要看滴,之后有时间?应该会看,嘎!
// UVa122 Trees on the level
// Rujia Liu
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 256 + 10;
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(); }
bool failed;
void addnode(int v, char* s) {
int n = strlen(s);
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;
}
void remove_tree(Node* u) {
if(u == NULL) return;
remove_tree(u->left);
remove_tree(u->right);
delete u;
}
char s[maxn];
bool read_input() {
failed = false;
remove_tree(root);
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() {
vector<int> ans;
while(read_input()) {
if(!bfs(ans)) failed = 1;
if(failed) printf("not complete\n");
else {
for(int i = 0; i < ans.size(); i++) {
if(i != 0) printf(" ");
printf("%d", ans[i]);
}
printf("\n");
}
}
return 0;
}