嘿,我正在編寫一個程序,它接收二進制樹的字符串表示並從中創建一個樹。代碼對我來說完全有意義,但它仍然不會做它應該做的。感謝大家。下面是一些代碼:BinTree與BinTree的括號表示法
(((()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;
}
你的樹結構(左)根(右)? – shoebox639 2010-12-10 17:09:40
是的,我認爲是的。 – 2010-12-10 17:14:30