二叉树是表达式处理的常用工具。
当我们输入一个表达式的时候:a+b*(c-d)-e/f ,那么给二叉树中的每个节点一个字符,这个二叉树可以构成我们所需要的表达式。
那么,我给你一个表达式后,你是如何建立一棵和这个表达式一样的树呢?
问题:
找到这个表达式中最后运算的符号。
代码:
# include<cstdio>
# include<iostream>
# include<cstring>
using namespace std;
# define MAX 12345
char s[MAX];
int lch[MAX],rch[MAX];//每个结点的左右子结点的编号
char op[MAX];//每个结点所存储的字符
int nc = 0;//结点数
int build( char *s ,int x,int y )
{
int c1 = -1,c2 = -1;
int p = 0;
int u = 0;
if ( y-x==1 )
{
u = ++nc;
lch[u] = rch[u] = 0;
op[u] = s[x];
return u;
}
for ( int i = x;i < y;i++ )
{
switch(s[i])
{
case ‘(‘:p++;break;
case ‘)‘:p--;break;
case ‘+‘:case ‘-‘:if (!p) c1 = i;break;
case ‘*‘:case ‘/‘:if (!p) c2 = i;break;
}
}
if ( c1<0 )
c1 = c2;
if ( c1<0 )
return build(s,x+1,y-1);
u = ++nc;
lch[u] = build(s,x,c1);
rch[u] = build(s,c1+1,y);
op[u] = s[c1];
return u;
}
int main(void)
{
while ( scanf("%s",&s)!=EOF )
{
int len = strlen(s);
int ans = build(s,0,len);
for ( int i = 0;i < len;i++ )
cout<<op[i]<<" ";
cout<<endl;
printf("%c\n",op[ans]);
}
return 0;
}
/*
a+b*(c-d)-e/f
*/
原文:http://www.cnblogs.com/lushichuanshuo/p/4856177.html