Trees on the level UVa 122
来源:互联网 发布:知乎miya的米牙 编辑:程序博客网 时间:2024/06/10 14:19
https://vjudge.net/problem/UVA-122
学习的第一个关于树的题目,按着紫书上的思路来的。再整理一下
#include<iostream>#include<cstdio>#include<queue>#include<cstring>using namespace std;struct Node{//结点的结构体 bool have_value; int v; Node *left,*right; Node():have_value(false),left(NULL),right(NULL){}};vector<int> ans;void addnode(int v,char* s);Node * root;bool failed;Node*newnode(){return new Node();}const int maxn = 300;char s[maxn];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);//strchr :查找字符串s中首次出现字符c的位置。 } return true;}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;}bool bfs(){//遍历树,储存数据到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(){ while(read_input()) { if(bfs()&&!failed){ for(vector<int>::iterator it = ans.begin();it!=ans.end();it++) { if(it!=ans.begin()) cout << " " ; cout<<*it; } cout <<endl; } else{ cout <<"not complete"<<endl;} } return 0;}
阅读全文
0 0
- UVa Problem 122 - Trees on the level
- UVA 122 - Trees on the level
- uva 122 - Trees on the level
- uva 122 Trees on the level
- UVA-122-Trees on the level
- UVA - 122 Trees on the level
- UVa 122 - Trees on the level
- UVa 122 - Trees on the level
- Uva 122 Trees on the level
- UVA - 122 Trees on the level
- UVa 122 - Trees on the level
- UVA - 122 Trees on the level Map
- Uva - 122 - Trees on the level
- uva 122 - Trees on the level
- UVa 122 Trees on the level
- uva 122 Trees on the level
- UVa 122 - Trees on the level
- UVa 122 Trees on the level
- eclipse更改J2EE对应的Web版本
- 安卓设置全屏或者无标题
- 基础题目--树
- console 问题
- gson序列化对象(值为空也序列化、值为null转换为""、排除策略)
- Trees on the level UVa 122
- 深度解析栈操作
- 今日头条笔试题
- android studio 使用lint工具
- 计算机视觉与深度学习公司
- RedHat6.5上Opencv的编译和部署
- 【基础中心】笔记六--选中动态表格的一行
- RecordSet.GetRows
- Java NIO使用及原理分析(三)