UVA 11234 - Expressions

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

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

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();		
		}
		else
			root[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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值