例如:a+b*(c-d)- e/f用二叉树表示出来
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
//#define max 100
int lch[100],rch[100];char op[100];
int nc=0;
int build_tree(string s,int x,int y){
int u;int p=0;
int c1=-1,c2=-1;
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_tree(s,x+1,y-1);//整个表达式被一对括号括起来
u = ++nc;
lch[u] = build_tree(s,x,c1);//以最后一个运算符为分界分成两部分,递归左子树
rch[u] = build_tree(s,c1+1,y);//递归右子树
op[u] = s[c1];
return u;
}
int main(){
string s;
cin>>s;
int n = build_tree(s,0,s.size());
cout<<n<<endl;
for(int i=1;i<=nc;i++)
cout<<op[i]<<" ";
cout<<endl;
return 0;
}