二叉树--uva122 结构体+指针解法
来源:互联网 发布:电脑桌面工作提醒软件 编辑:程序博客网 时间:2024/06/07 04:44
题意:输入一个二叉树,让你按照从上到下,从左到右的顺序输出这颗二叉树。
分析:哈哈哈,终于自己不看书实现了一次,激动人心啊!
/*@Filename: test.cpp@Author: wyl6 @Mail: ustbcs_wyl@163.com@Thought:*/#include <cstdio>#include <cstdlib>#include <iostream>#include <stack>#include <queue>#include <algorithm>#include <cstring>#include <string>#include <cmath>#include <vector>#include <bitset>#include <list>#include <sstream>#include <set>#include <functional>using namespace std;const int MAX = 100;char s[MAX];bool faild;struct node{ int v; node * left,*right; bool have_Value; node():v(0),left(NULL),right(NULL),have_Value(false){}};node *root;node *NewNode(){ return new node();}void Del_Tree(node *u){ if(u == NULL) return; Del_Tree(u->left); Del_Tree(u->right); delete u;}void AddNode(int v,char *s)//字符数组传入字符指针变量{ int len = strlen(s); node *t = root; for (int i = 0; i < len; ++i){ if (s[i] == 'L'){ if(t->left == NULL) t->left = NewNode(); t = t->left; }else if (s[i] == 'R'){ if(t->right == NULL) t->right = NewNode(); t = t->right; } } if(t->have_Value) faild = true; t->v = v; t->have_Value = true;}bool Input_Tree(){ root = NewNode(); faild = false; for (;;){ if(scanf("%s",s) != 1) return false; if(!strcmp(s,"()")) break; //相同返回0,不同返回1 int v; sscanf(&s[1],"%d",&v); //sscanf(a,b,c),从a中读取b格式的数据,存入c中 AddNode(v,strchr(s,',')+1);//strchr(str,c)从str中找到c的第一个位置 } 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(){ while(1) { Del_Tree(root); if(!Input_Tree()) break; vector<int> ans; if(!faild && Bfs(ans)){ int len = ans.size(); for (int i = 0; i < len; ++i) cout << ans[i] << (i == (len-1)?'\n':' '); }else cout << "not complete" << endl; } return 0;}
参考:刘大爷的紫书第六章
阅读全文
0 0
- 二叉树--uva122 结构体+指针解法
- uva122 Trees on the level(锻炼指针建一棵二叉树)
- UVA679 / UVA122 学习二叉树
- uva122 数组表示二叉树,bfs
- uva122(二叉树建立,中序遍历)
- UVA122二叉树BFS广搜入门
- uva122--二叉树的层次遍历
- UVa122 二叉树的层次遍历
- UVa122二叉树的层次遍历
- UVA122 Trees on the level【二叉树】【BFS】
- Trees on the level(UVA122,二叉树的建立)
- Uva122 Trees on the level 二叉树的数组实现
- 二叉树的树状数组和双向列表有区别,一个是针对明显的树状结构,一个是可以用来表示树状结构,Uva122
- uva122(不用二叉树也能做)
- uva122
- uva122
- UVA122
- uva122
- 栈及栈的应用(括号匹配和逆波兰表达式)
- python学习笔记 第十二章
- Sublime Text 3 Build 3155 & 3156 License
- Class.forName()用法详解
- ngx-bootstrap学习笔记(一)-popover
- 二叉树--uva122 结构体+指针解法
- log4j
- 个人简介
- Effective STL学习笔记-条款44
- 开始机器学习
- 微服务架构适用场景分析
- 云服务模式:SaaS、PaaS和IaaS
- 数据结构实验之图论五:从起始点到目标点的最短步数(BFS)
- HDU2052