开发者

Parenthesis representation of BinTree to BinTree

Hey all, I'm writing a program that takes in a string representation of a binary tree and creating a tree out of it. The code makes complete sense to me but it still wont do what it should. Thanks everyone. Here is some code:

(((()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开发者_JAVA技巧)));
            }
        }
        i++;
    }
    return null;
}


Start debugging by inspecting the values of s for each call to findRoot(). The code looks good, except that I have a feeling you have off-by-one errors in your substring() parameters.


I see that when you've found your root, you recursively call findRoot on the everything left of the root and everything on the right. Or meant to anyway. The call for the left child removes the parenthesis around it, but the right one doesn't. Seeing as you find a leaf node by checking for string length of 3, you want to keep the parens. So the left child call should be: findRoot(tree.substring(0, i).


Sorry: my low rep doesn't allow me to comment directly, so I need to ask my question via this answer. Is

(((()B(C))D(E))F(G))J(()K((L)M(T)))

an example string input - representation of a binary tree. If so, can you provide in word form just a bit of the tree. Just a couple of the leaves would do the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜