Search code examples
javarecursiontreebinary-treeparentheses

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)));
            }
        }
        i++;
    }
    return null;
}

Solution

  • 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.