4.2.2 构造一棵表达式树
代码如下:
#include <iostream>
#include <string>
#include <sstream>
#include <stack>
using namespace std;
typedef char ELEMENT;
typedef struct TreeNode
{
ELEMENT vlaue;
struct TreeNode *lchild;
struct TreeNode *rchild;
}*Bitree;
/*
中序遍历
*/
void infix_view(Bitree);
int main()
{
string str;
cin >> str;
istringstream istream(str); //string流,内存IO,定义后直接初始化
char word;
stack<Bitree> m_stack;
while (istream >> word){ //当遇到结束符时,流错误,退出while
if (word == '+' || word == '-' || word == '*' || word == '/'){
Bitree p;
p = (Bitree)malloc(sizeof(TreeNode));
p->vlaue = word;
p->rchild = m_stack.top(); //返回栈顶元素,但不将元素弹栈
m_stack.pop();//弹出栈顶元素,但不返回值
p->lchild = m_stack.top();
m_stack.pop();
m_stack.push(p);
}
else{
Bitree q;
q = (Bitree)malloc(sizeof(TreeNode));
q->vlaue = word;
q->lchild = NULL;
q->rchild = NULL;
m_stack.push(q);
}
}
Bitree root = m_stack.top();
m_stack.pop();
infix_view(root);
cout << endl;
// 注意,malloc 后应该 free 释放树
system("pause");
}
void infix_view(Bitree tree)
{
if (tree){
if (tree->lchild)infix_view(tree->lchild);
cout << tree->vlaue;
if (tree->rchild)infix_view(tree->rchild);
}
}