对二叉树进行前序遍历、中序遍历、后续遍历

/*
  Name: 表达式求值 
  Description: 为了实现表达式求值,可以首先读入原表达式(包括括号)并创建对应二叉树,
  其次对二叉树进行前序遍历、中序遍历、后续遍历,输出对应的逆波兰表达式、中序表达式和波兰表达式。
*/

#include<string>
#include<iostream>
using namespace std;

//=================结点类=====================
class Node
{
	friend class Tree;
public:
	Node()
	{
		lchild = NULL;
		key = '\0';
		rchild = NULL;
	}
protected:
private:
	Node *lchild;
	char key;
	Node *rchild;
};

//===================二叉树类=================

class Tree
{
public:
	void rootLast(Node *p);	//先序遍历二叉树
	void rootMiddle(Node *p);	//中序遍历二叉树
	void rootFirst(Node *p);	//后续遍历二叉树
	void Creat(Tree &L,string exp);	//以中序生成二叉树

	Tree()
	{
		root = NULL;
	}
	Node *root;
protected:
private:
};

//======================以中序生成二叉树=============
void Tree::Creat(Tree &L,string exp)
{
	Node *s = new Node;
	s->key = exp[0];
	L.root = s;
	int i = 1;
	while(exp[i] != '\0'){
		Node *p = new Node;
		p->key = exp[i];
		if(i % 2 == 1){
			p->lchild = L.root;
			L.root = p;
		}else{
			L.root->rchild = p;
		}
		i++;
	}
}

//===========后序遍历二叉树,输出波兰表达式===========
void Tree::rootFirst(Node *p)
{

	if(p != NULL)
	{
		cout << p->key;
		rootFirst(p->lchild);
		rootFirst(p->rchild);
	}
}

//==========中序遍历二叉数,输出中缀表达式=============

void Tree::rootMiddle(Node *p)
{
	if(p != NULL)
	{
		rootMiddle(p->lchild);
		cout << p->key;
		rootMiddle(p->rchild);
	}
}
//===========后序遍历二叉树,输出逆波兰表达式============

void Tree::rootLast(Node *p)
{
	if(p != NULL)
	{
		rootLast(p->lchild);
		rootLast(p->rchild);
		cout << p->key;
	}
}

//========================主函数=============================

int main()
{
	cout << "请输入表达式: \t";
	string exp;
	cin >> exp;
	cout << '\n';
	
	Tree L;
	L.Creat(L,exp);

	cout << "波兰表达式; \t";
	L.rootFirst(L.root);
	cout << '\n' << '\n';

	cout << "中缀表达式 \t";
	L.rootMiddle(L.root);
	cout << '\n' << '\n';

	cout <<"逆波兰表达式: \t";
	L.rootLast(L.root);
	cout << '\n' << '\n';

    system("pause");
	return 0;
}


你可能感兴趣的:(中序遍历,前序遍历,后续遍历)