BinTree parenthesis representation for BinTree

Hi everyone, I am writing a program that takes a string representation of a binary tree and creates a tree from it. The code makes full sense to me, but it still won’t do what it should. Thanks to all. Here is the 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;
}
+3
source share
3 answers

Run debugging by checking the values sfor each call findRoot(). The code looks good, except that I have the feeling that you have errors "in turn" in your parameters substring().

+1
source

, , findRoot , . . , - . , node, 3, parens. , left child : findRoot(tree.substring(0, i).

0

: , .

(((() ()) D ()) F (G)) J (() ((L), ()))

- . , . .

0

Source: https://habr.com/ru/post/1779632/


All Articles