C++二叉树计算表达式
来源:易贤网 阅读:2167 次 日期:2015-04-16 15:47:14
温馨提示:易贤网小编为您整理了“C++二叉树计算表达式”,方便广大网友查阅!

C++二叉树计算表达式,具体代码如下:

#include <iostream>

using namespace std;

class calc

{

enum Type {DATA, ADD, SUB, MULTI, DIV, OPAREN, CPAREN, EOL};

struct node

{

Type type;

int data;

node *lchild, *rchild;

node(Type t, int d=0, node *lc=NULL, node *rc=NULL)

{

type=t; data=d; lchild=lc; rchild=rc;

}

};

node *root;

node *create(char * &s);

Type getToken (char * &s, int &value);

int result (node *t);

public:

calc (char *s)

{

root=create(s);

}

int result()

{

if (root==NULL) return 0;

return result(root);

}

};

calc::node *calc::create(char * &s)

{

node *p, *root=NULL;

Type returnType,flag=DATA;

int value;

while (*s)

{

flag=returnType;

returnType=getToken(s,value);

switch (returnType)

{

case DATA:

case OPAREN:

if (returnType == DATA) p=new node(DATA,value);

else p=create(s);

if (root==NULL) root=p;

else if (root->rchild==NULL) root->rchild=p;

else root->rchild->rchild=p;

break;

case CPAREN:

case EOL: return root;

case ADD:

case SUB:

root=new node(returnType,0,root);

break;

case MULTI:

case DIV:

if (root->type==DATA || root->type==MULTI || root->type==DIV || flag==OPAREN)

root=new node(returnType,0,root);

else

root->rchild=new node(returnType,0,root->rchild);

}

}

return root;

}

calc::Type calc::getToken(char *&s, int &data)

{

char type;

while (*s==' ') ++s;

if (*s>='0' && *s<='9')

{

data=0;

while (*s>='0' && *s<='9') {data=data*10+ *s-'0'; ++s;}

return DATA;

}

if (*s == '\0') return EOL;

type =*s; ++s;

switch(type)

{

case '+':return ADD;

case '-':return SUB;

case '*':return MULTI;

case '/':return DIV;

case '(':return OPAREN;

case ')':return CPAREN;

default: return EOL;

}

}

int calc::result(node *t)

{

int num1,num2;

if (t->type == DATA) return t->data;

num1=result(t->lchild);

num2=result(t->rchild);

switch(t->type)

{

case ADD:t->data=num1+num2;break;

case SUB:t->data=num1-num2;break;

case MULTI: t->data=num1*num2;break;

case DIV:t->data=num1/num2;break;

}

return t->data;

}

int main()

{

char expression[256];

cin>>expression;

calc exp(expression);

cout<<exp.result()<<endl;

return 0;

}

更多信息请查看IT技术专栏

更多信息请查看技术文章
易贤网手机网站地址:C++二叉树计算表达式
由于各方面情况的不断调整与变化,易贤网提供的所有考试信息和咨询回复仅供参考,敬请考生以权威部门公布的正式信息和咨询为准!
关于我们 | 联系我们 | 人才招聘 | 网站声明 | 网站帮助 | 非正式的简要咨询 | 简要咨询须知 | 加入群交流 | 手机站点 | 投诉建议
工业和信息化部备案号:滇ICP备2023014141号-1 云南省教育厅备案号:云教ICP备0901021 滇公网安备53010202001879号 人力资源服务许可证:(云)人服证字(2023)第0102001523号
云南网警备案专用图标
联系电话:0871-65317125(9:00—18:00) 获取招聘考试信息及咨询关注公众号:hfpxwx
咨询QQ:526150442(9:00—18:00)版权所有:易贤网
云南网警报警专用图标