本来挺简单一个问题结果折腾了有几天。
网上也没有比较合理的答案。
需要两个栈,一个栈存储操作符,另一个栈存储树或者节点。
代码如下:
main:
#include"Expression_bitree.h"
Status print(Data i)
{
using namespace std;
if (i.ischar)
cout << (char)i.data;
else
cout << i.data;
system("pause");
return OK;
}
int main()
{
using namespace std;
BiTree pine = NULL;
CreateBiTree(pine, "1+2*(3-4)-5/6");
cout << "create finished" << endl;
system("pause");
PreOrderTraverse(pine, print);
system("pause");
}
Stack.h:
#ifndef STACK_H_
#define STACK_H_
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 5
#ifndef Status
#define Status int
#define OK 1
#define ERROR 0
#define OVERFLOW 2
#endif
#include<cstdlib>
#include<malloc.h>
template<class sElemType>
class Stack
{
private:
sElemType* base;
sElemType* top;
int stacksize;
public:
Stack();
~Stack();
Status ClearStack();
bool StackEmpty();
int StackLength() { return stacksize; }
Status GetTop(sElemType & e);
Status Push(sElemType e);
Status Pop(sElemType & e);
Status StackTraverse(Status(*visit)(sElemType t));
};
template<class sElemType>
Stack<sElemType>::Stack()
{
base = (sElemType*)malloc(STACK_INIT_SIZE*sizeof(sElemType));
if (!base) exit(OVERFLOW);
top = base;
stacksize = STACK_INIT_SIZE;
}
template<class sElemType>
Status Stack<sElemType>::GetTop(sElemType & e)
{
if (top == base) return ERROR;
e = *(top - 1);
return OK;
}
template<class sElemType>
Status Stack<sElemType>::Push(sElemType e)
{
if (top - base >= stacksize)
{
base = (sElemTyp