UVA11234- Expressions

题意:题目给你一种后缀操作表达式,x,y +的形式,然后要求我们转换成queue的方式

思路:其实刚开始看到这个,很蒙。。没有什么思绪。。。想了很久,就去看了别人的思路。

             小写其实是代表数字,大写字母代表操作符。当遇到小写就将其当作无子树的节点压入栈中,遇到大写字母就将栈顶前两个节点取出,作为遇到的这个大写字母的左右子 树。然后在栈中删除取出的两个节点,将新的节点压入栈中。如此循环下去,知道树建好。

             主要就是要利用stack建立二叉树,利用queue进行层次遍历,然后将结果逆序输出

#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;

struct Node{
	char data;
	int left;
	int right;
};

stack<int> s;
queue<int> q;
Node arr[10005];
char str[10005];
char answer[10005];
int cnt;

void bfs(int root) {
	while (!q.empty())
		q.pop();
	q.push(root);
	answer[cnt++] = arr[root].data;//先将头节点存起来

	while (!q.empty()) {
		int t = q.front();	
		q.pop();	
		if (arr[t].left != -1) {
			answer[cnt++] = arr[arr[t].left].data;
			q.push(arr[t].left);	
		}	
		if (arr[t].right != -1) {
			answer[cnt++] = arr[arr[t].right].data;
			q.push(arr[t].right);	
		}
	}
}//层次遍历

void Build() {
	while (!s.empty())
		s.pop();
	for(int i = 0; i < strlen(str); i++) {
		if (islower(str[i])) {	
			s.push(i);
			arr[i].data = str[i];
			arr[i].left = -1;
			arr[i].right = -1;
		}//遇到小写字母就将其压入栈内
		else {
			int r = s.top();	
			s.pop();	
			int l = s.top();	
			s.pop();
			arr[i].data = str[i];
			arr[i].left = l;
			arr[i].right = r;
			s.push(i);
		}//遇到大写字母,就将栈顶的头两个节点取出,赋给新节点的左右儿子,并将新的节点压入栈内
	}
}//利用stack建二叉树

int main() {
	int cas;
	scanf("%d", &cas);
	while (cas--) {
		scanf("%s", str);	
		cnt = 0;

		Build();				
		bfs(s.top());

		for(int i = cnt - 1; i >= 0; i--)//逆序输出
			printf("%c", answer[i]);
		printf("\n");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值