用二叉树写中缀表达式

参考数据结构与算法分析 C++描述。代码如下:

#include <iostream>
#include <stack>
#define ISCHAR 1
#define ISOPERATOR 2
#define OTHER 0
using namespace std;
struct BinaryNode
{
	char c;
	BinaryNode *left;
	BinaryNode *right;
	BinaryNode(char _c,BinaryNode *node1,BinaryNode *node2)
	{
		c=_c;
		left=node1;
		right=node2;
	}
};
int isCharOrOperator(char c)
{
	if(c>='a' && c<='z' || c>='A' && c<='Z')
		return ISCHAR;
	if(c=='+' || c=='-' || c=='*' || c=='/')
		return ISOPERATOR;
	return OTHER;

}
void traverse(BinaryNode *node)
{
	if (node!=NULL)
	{
		traverse(node->left);
		cout<<node->c;
		traverse(node->right);
	}
}
int main()
{
	stack<BinaryNode *> charStack;
	char c='0';
	while(cin>>c && c!='0')
	{
		if(ISCHAR==isCharOrOperator(c))
		{
			BinaryNode* node=new BinaryNode(c,NULL,NULL);
			charStack.push(node);
		}
		else if(ISOPERATOR==isCharOrOperator(c))
		{
			BinaryNode *rightNode=charStack.top();
			charStack.pop();
			BinaryNode *leftNode=charStack.top();
			charStack.pop();
			BinaryNode *node=new BinaryNode(c,leftNode,rightNode);
			charStack.push(node);
		}
	}

	while (!charStack.empty())
	{
		BinaryNode *node=charStack.top();
		traverse(node);
		charStack.pop();
	}

}

输入ab+cde+**,输出为a+b*c*d+e

你可能感兴趣的:(用二叉树写中缀表达式)