利用二叉树实现前中后缀表达式的相互转换

多写几个表达式对应的前中后缀形式就可以发现,中缀表达式、前缀表达式、后缀表达式就是一棵二叉树的中序、前序、后序遍历的结果(当然由于中缀表达式会有运算符优先级的问题,可能中间会有括号,但是如果去掉括号就完全和中序遍历结果一致了)。

因此,如果我们能根据其中某一个形式的表达式创建出对应的二叉树,不就能得到对应的另外两种形式的表达式了吗。

后缀转前缀中缀

#include <iostream>
#include <cstdio>
#include <malloc.h>
#include <string>
#include <stack>

using namespace std;

typedef struct Node
{
	char* data;
	Node* l, * r;
}TNode, * Tree;

void InOrder(Tree& t)
{
	if (t == NULL) return;
	if (t->l == NULL && t->r == NULL) printf("%s ", t->data);
	else
	{
		printf("( ");
		InOrder(t->l);
		printf("%s ", t->data);
		InOrder(t->r);
		printf(") ");
	}
}

void PreOrder(Tree& t)
{
	if (t == NULL) return;
	if (t->l == NULL && t->r == NULL) printf("%s ", t->data);
	else
	{
		printf("%s ", t->data);
		PreOrder(t->l);
		PreOrder(t->r);
	}
}

int main()
{
	string str;
	getline(cin, str);
	Tree t = (Tree)malloc(sizeof(TNode));

	stack<Tree> stk;
	for (int i = 0; str[i]; ++i)
	{
		if (str[i] == ' ') continue;
		TNode* temp = (Tree)malloc(sizeof(TNode));
		temp->l = NULL, temp->r = NULL;
		if (!isdigit(str[i]))
		{
			temp->data = (char*)malloc(sizeof(char)+1);
			temp->data[0] = str[i];
			temp->data[1] = '\0';

			TNode* b = stk.top(); stk.pop();
			TNode* a = stk.top(); stk.pop();
			temp->l = a, temp->r = b;
		}
		else
		{
			int j = i + 1;
			while (isdigit(str[j])) j++;
			temp->data = (char*)malloc(sizeof(char) * (j - i + 1));
			for (int k = i; k < j; ++k) temp->data[k - i] = str[k];
			temp->data[j - i] = '\0';
			i = j - 1;
		}
		stk.push(temp);
	}
	t->l = stk.top();

	InOrder(t->l);
	puts("");
	PreOrder(t->l);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值