uva 11234

本文介绍了一种通过栈和队列实现的表达树构建方法,并利用层次遍历逆序输出表达式的算法。该方法首先读取字符串,使用栈来构建表达树,再通过队列进行层次遍历并将结果逆序输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意 :实际上就是让我们建树,然后遍历树,逆序输出。。


#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <stack>
using namespace std;

class Node
{
	public :
		char data;
		int left,right;
}node[10005];
char s[10005];
stack<int >st;
queue<int >qu;
int result[10005],inpos;

void bfs(int root)  //从根节点开始层次遍历,记录结果
{
	while(!qu.empty())
		qu.pop();
	qu.push(root);
	result[inpos++] = node[root].data;  
	while(!qu.empty())
	{
		int t = qu.front();  //拿出一个节点开始遍历
		qu.pop();
		if(node[t].left != -1)
		{
			result[inpos++] = node[node[t].left].data;
			qu.push(node[t].left);   // 队是先进先出的
		}
		if(node[t].right != -1)
		{
			result[inpos++] = node[node[t].right].data;
			qu.push(node[t].right);
		}
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	getchar();
	while(t--)
	{
		scanf("%s",s);
		while(!st.empty())
			st.pop();
		for(int i =	0 ; i < strlen(s) ; i++ )
		{
			if(s[i]>='a' && s[i]<= 'z')
			{
				st.push(i);    // 我们每次入栈的是根节点
				node[i].data = s[i];
				node[i].left = -1;
				node[i].right = -1;
			}
			else
			{
				int r = st.top();
				st.pop();
				int l = st.top();
				st.pop();
				node[i].data = s[i];  // 构建一棵小树,然后还是根节点入栈
				node[i].left = l;
				node[i].right = r;
				st.push(i);
			}
		}
		inpos = 0;
		bfs(st.top());  
		for(int i = inpos-1 ; i >= 0 ; i--)   // 倒序输出
			printf("%c",result[i]);
		printf("\n");
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值