public static String test2pro(String str) {
int i=0;
String temp="";
while(i<str.length()&&str.charAt(i)!='(') {
i++;
}
if(i==str.length()) {
temp= str.substring(0);
}else if(str.charAt(i)=='(') {
temp = str.substring(0,i);
String rest = str.substring(i+1,str.length()-1);
i=0;
int count=0;
while(i<rest.length()) {
char t =rest.charAt(i);
if(t=='(') {
count++;
}else if(t==')') {
count--;
}else if(t==',') {
if(count==0)
break;
}
i++;
}
if(i==0) {
temp+=test2pro(rest.substring(i+1,rest.length()));
}else if(i==temp.length()-1) {
temp = test2pro(rest.substring(0,i))+temp;
}else {
temp+=test2pro(rest.substring(i+1,rest.length()));
temp = test2pro(rest.substring(0,i))+temp;
}
}
return temp;
}
这个是我改进的代码,不用去构造二叉树了,直接遍历字符串加递归,应该没什么问题。