算法分析:
转变成后缀表达式的算法,因此可以从这两种输入表达式生成表达式树。所
描述的方法类似于后缀表达式求值的算法。我们一次一个符号的读入表达式
。如果符号是操作数,那么就建立一个单结点树并将它推入栈中。如果符号
是操作符,他的左、右儿子分别是T1和T2。然后将指向这棵树的指针压入栈
中。
例如输入123*+,将会得到相应的表达式+1*23、1+2*3、12*3+。
个人小结及心得:
在本程序的编写过程中,遇到的最大问题当然表达式树的
创建。对于TreeNode这个结构体,以及new的使用给我带来了许
多大的麻烦。TreeNode p1,TreeNode* p1,TreeNode* &p1有时让
我觉得手足无措,好在经过好多次的debug之后,程序才勉强可
以运行,同时对上述三个类型有了更好的理解。
另外,本程序的局限在于在表达式的读入过程中,读入的
表达式必须为后缀表达式,以及相应的字符必须为数字,如果
不能满足这两个条件则程序不能运行。其次,本程序利用递归
的思想遍历该树,也对程序的运行速度不能保证。另外,由于
本人水平有限,在遍历树的过程中不会生成树的样子,暂且就
先这样,不过在之后的学习中,我相信其一定难不倒我。
代码实现:
#include <iostream>
#include<stack>
#include<string>
using namespace std;
struct TreeNode
{
string element;
TreeNode* left;
TreeNode* right;
TreeNode(TreeNode* m=NULL,TreeNode* n=NULL):left(m),right(n){}
};
void construct_tree(const string& str,stack<TreeNode*>&ST)
{
char CH;
for(int i=0;(CH=str[i])!='\0';++i)
{
if(CH>='0'&&CH<='9')//此时的读入仅限于数字
{
TreeNode* p1=new TreeNode;
(*p1).element=CH;
ST.push(p1);
}
else
{
struct TreeNode* p=new TreeNode;
(*p).element=CH;
struct TreeNode* p2=ST.top();
ST.pop();
struct TreeNode* p3=ST.top();
ST.pop();
(*p).left=p3;
(*p).right=p2;
ST.push(p);
}
}
}
void PreOrder(TreeNode* &T)//先序遍历
{
if(T!=NULL)
{
cout<<T->element; //只会这样输出 如何输出成树状 还有待研究
PreOrder(T->left);
PreOrder(T->right);
}
else
cout<<"";
}
void InOrder(TreeNode* &T)//中序遍历
{
if(T!=NULL)
{ InOrder(T->left);
cout<<T->element; //只会这样输出 如何输出成树状 还有待研究
InOrder(T->right);
}
else
cout<<"";
}
void PostOrder(TreeNode* &T)//后序遍历
{
if(T!=NULL)
{
InOrder(T->left);
InOrder(T->right);
cout<<T->element; //只会这样输出 如何输出成树状 还有待研究
}
else
cout<<"";
}
int main()
{
stack<TreeNode*>tree_stack;
cout<<"Please input the postfix equation(比如123*+,不可读入字母)"<<endl;
cout<<"**********"<<endl;
string postfix_equation;
getline(cin,postfix_equation);
construct_tree(postfix_equation,tree_stack);
PreOrder(tree_stack.top());
cout<<"\n**********"<<endl;
InOrder(tree_stack.top());
cout<<"\n**********"<<endl;
PostOrder(tree_stack.top());
return 0;
}