UVA 11234

来源:互联网 发布:星星知我心第二部全集 编辑:程序博客网 时间:2024/06/13 22:17

题目大意:将在栈里的存储方式,转换成在队列里的存储,也就是输入二叉树的先序遍历,输出二叉树的层次遍历的逆。

解题思路:先用栈构建二叉树,碰到小写字母(小写字母的位置入栈),建树(叶子节点)。碰到大写字母时,出栈两个(其左右节点的位置),建树,大写字母的位置入栈。建完树以后,遍历一次,逆写入字符串。最后输出就可以了。

ac代码:

#include <iostream>#include <cstring> #include <stack>#include <queue>using namespace std;struct tree{char data;int left;int right;}root[10005];struct node{char no;int de;};queue <tree>qu;int n, m, len;char ch[10005], a[10005];stack <node>st;void build(){for (int i=0; i<len; i++){root[i].data = ch[i];node temp;temp.no = ch[i];temp.de = i;if (ch[i] <= 'Z'){root[i].right = st.top().de;st.pop();root[i].left = st.top().de;st.pop();}elseroot[i].right = root[i].left = -1;st.push(temp);}}void bfs(){int cnt=len-1;tree temp;qu.push(root[len-1]);while (!qu.empty()){temp = qu.front();qu.pop();a[cnt--] = temp.data;if (temp.left != -1)qu.push(root[temp.left]);if (temp.right != -1)qu.push(root[temp.right]);}}int main(){scanf("%d", &n);while (n--){scanf("%s", ch);len = strlen(ch);build();bfs();printf("%s\n",a);memset(a, 0, sizeof(a));}return 0;}
原创粉丝点击