uva11234 Expression (二叉树重建+层次遍历)

题意:具体没理解。我知道我这样回答很坑。 根据后缀表达式重建树, 然后输出层次遍历的逆序。

  

思路: 如何建树?从左往右读入字符, 遇到小写字符建一个结点压入栈中, 遇到一个大写字母建一个结点, 其左右子树便是栈顶的前两个, 构成的新树再压入栈中。 最后只剩一棵树。 然后对这棵树层次遍历(BFS), 输出层次遍历的逆序。


算法复杂度: 缺。


代码:

/*建树*/
#include <cstdio>
#include <cctype>
#include <stack>
#include <queue>
using namespace std;

struct SNode
{
	SNode(char ltr = 'a') {
		left = NULL;
		right = NULL;
		letter = ltr;
	}
	char letter;
	SNode *left;
	SNode *right;
};

void queueOrder(SNode *);
void removeNode(SNode *&);

int main()
{
	int cases;
	scanf("%d%*c", &cases);
	while (cases--) {
		//init
		char ch;
		stack<SNode *> sta;
		while (!sta.empty()) {
			sta.pop();
		}

		while ((ch = getchar()) != '\n') {
			if (islower(ch)) {
				sta.push(new SNode(ch));
			}else if (isupper(ch)) {
				SNode *root = new SNode(ch);
				root->right  = sta.top(); sta.pop();
				root->left = sta.top(); sta.pop();
				sta.push(root);
			}
		}
		
		SNode *root = sta.top(); sta.pop();

		//output
		queueOrder(root);

		//free
		removeNode(root);

	}

	return 0;
}

void queueOrder(SNode *star)
{
	stack<char> squ;
	queue<SNode *> que;

	que.push(star);
	squ.push(star->letter);

	while (!que.empty()) {
		SNode *root = que.front();
		que.pop();

		if (root->left != NULL) {
			squ.push(root->left->letter);
			que.push(root->left);
		}

		if (root->right != NULL) {
			squ.push(root->right->letter);
			que.push(root->right);
		}
	}

	while (!squ.empty()) {
		printf("%c", squ.top());
		squ.pop();
	}
	printf("\n");
}

void removeNode(SNode *&root)
{
	if (root == NULL) {
		return;
	}
	removeNode(root->left);
	removeNode(root->right);

	delete root;
	root = NULL;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值