大家好,我正在编写一个程序,该程序接收二叉树的字符串表示形式并将其创建为一棵树。虽然代码对我来说非常清晰,但它仍然不能按照预期工作。谢谢大家。以下是一些代码:
(((()B(C))D(E))F(G))J(()K((L)M(T)))
private static BinTree<String> findRoot(String s){
String tree = s;
int i = 0;
int count = 0;
String root;
if(tree.equalsIgnoreCase("()")){
return null;
}
if(tree.length()==3){
return new BinTree<String>(Character.toString(tree.charAt(1)));
}
while(i<tree.length()){
if(tree.charAt(i)=='('){
count++;
}
if(tree.charAt(i)==')'){
count--;
if(count==0){
i++;
root = Character.toString(tree.charAt(i));
return new BinTree<String>(root, findRoot(tree.substring(1, i-1)), findRoot(tree.substring(i+1)));
}
}
i++;
}
return null;
}